{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"baseline_logs":"[{\"baseline\":\"a9d7ced84989ec05be09b4b8428759ef60450a0f (a9d7ced84989ec05be09b4b8428759ef60450a0f)\",\"status\":\"Applied\",\"log\":\"Trying baseline: a9d7ced84989ec05be09b4b8428759ef60450a0f (a9d7ced84989ec05be09b4b8428759ef60450a0f)\\nApplication successful.\\n\"}]","can_release_embargo":false,"can_view_embargoed":false,"cc":"\"Andrew Davis\" <afd@ti.com>, \"Pratham T\" <t-pratham@ti.com>, \"Kamlesh Gurudasani\" <kamlesh@ti.com>, \"Udit Kumar\" <u-kumar1@ti.com>, linux-crypto@vger.kernel.org, linux-kernel@vger.kernel.org, \"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466150,"dry_run":false,"embargo_until":null,"failed_reason":null,"id":74414,"limit":50,"mailing_lists":["LKML","linux-crypto"],"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","model_name":"gemini-3.1-pro-preview","mr_url":null,"page":1,"patches":[{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189868,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-1-57ab34e97162@ti.com","msg_db_id":519587,"part_index":1,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 01/30] crypto: sa2ul - remove dead code"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189869,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-2-57ab34e97162@ti.com","msg_db_id":519588,"part_index":2,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 02/30] crypto: sa2ul - remove totally unused structure fields"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189870,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-3-57ab34e97162@ti.com","msg_db_id":519589,"part_index":3,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 03/30] crypto: sa2ul - remove unused algorithm ID fields"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189864,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-4-57ab34e97162@ti.com","msg_db_id":519583,"part_index":4,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 04/30] crypto: sa2ul - remove unused fields from sa_cmdl_cfg"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189865,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-5-57ab34e97162@ti.com","msg_db_id":519584,"part_index":5,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189866,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-6-57ab34e97162@ti.com","msg_db_id":519585,"part_index":6,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 06/30] crypto: sa2ul - remove unused macro definitions"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189871,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-7-57ab34e97162@ti.com","msg_db_id":519590,"part_index":7,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 07/30] crypto: sa2ul - consolidate encryption offset definitions"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189872,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-8-57ab34e97162@ti.com","msg_db_id":519592,"part_index":8,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189874,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-9-57ab34e97162@ti.com","msg_db_id":519594,"part_index":9,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 09/30] crypto: sa2ul - remove unused base register pointer"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189875,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-10-57ab34e97162@ti.com","msg_db_id":519595,"part_index":10,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189867,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-11-57ab34e97162@ti.com","msg_db_id":519586,"part_index":11,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 11/30] crypto: sa2ul - remove unused line"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189885,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-12-57ab34e97162@ti.com","msg_db_id":519605,"part_index":12,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 12/30] crypto: sa2ul - remove redundant sa_sha_digest() wrapper"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189880,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-13-57ab34e97162@ti.com","msg_db_id":519600,"part_index":13,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 13/30] crypto: sa2ul - fix struct documentation for match_data"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189884,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-14-57ab34e97162@ti.com","msg_db_id":519604,"part_index":14,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 14/30] crypto: sa2ul - zero out security context on free"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189873,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-15-57ab34e97162@ti.com","msg_db_id":519593,"part_index":15,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 15/30] crypto: sa2ul - fix context release on errors"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189879,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-16-57ab34e97162@ti.com","msg_db_id":519599,"part_index":16,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 16/30] crypto: sa2ul - fix resource leak of sha in init_alg() error path"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189878,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-17-57ab34e97162@ti.com","msg_db_id":519598,"part_index":17,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189881,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-18-57ab34e97162@ti.com","msg_db_id":519601,"part_index":18,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189883,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-19-57ab34e97162@ti.com","msg_db_id":519603,"part_index":19,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 19/30] crypto: sa2ul - generate dynamic metadata length"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189890,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-20-57ab34e97162@ti.com","msg_db_id":519610,"part_index":20,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 20/30] crypto: sa2ul - fix command label stack corruption"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189882,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-21-57ab34e97162@ti.com","msg_db_id":519602,"part_index":21,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 21/30] crypto: sa2ul - fix error handling in sa_prepare_iopad"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189887,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-22-57ab34e97162@ti.com","msg_db_id":519607,"part_index":22,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 22/30] crypto: sa2ul - move export to appropriate location."},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189888,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-23-57ab34e97162@ti.com","msg_db_id":519608,"part_index":23,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 23/30] crypto: sa2ul - fix stack overflow in sa_prepare_iopads"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189891,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-24-57ab34e97162@ti.com","msg_db_id":519613,"part_index":24,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 24/30] crypto: sa2ul - add more checks before processing ipad/opad"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189886,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-25-57ab34e97162@ti.com","msg_db_id":519606,"part_index":25,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 25/30] crypto: sa2ul - fix data corruption by skipping device sync on unmap"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189892,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-26-57ab34e97162@ti.com","msg_db_id":519614,"part_index":26,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 26/30] crypto: sa2ul - use correct DMA direction in sa_sync_from_device"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189889,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-27-57ab34e97162@ti.com","msg_db_id":519609,"part_index":27,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189895,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-28-57ab34e97162@ti.com","msg_db_id":519618,"part_index":28,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 28/30] crypto: sa2ul - route requests through crypto_engine"},{"apply_error":null,"email_cc":"[]","email_status":"Skipped","email_to":"[]","id":189894,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-29-57ab34e97162@ti.com","msg_db_id":519617,"part_index":29,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 29/30] crypto: sa2ul - report SA engine hardware revision"},{"apply_error":null,"email_cc":"[]","email_status":"Muted","email_to":"[]","id":189893,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-30-57ab34e97162@ti.com","msg_db_id":519616,"part_index":30,"previous_patch":null,"status":"Reviewed","subject":"[PATCH 30/30] crypto: sa2ul - add AES-CM (SA3UL_CM) TRNG priming support"}],"previous_patchset_id":null,"prompts_git_hash":"0.4.0","provider":"gemini","received_parts":30,"reviews":[{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167762,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Missing lower bounds check and signed comparison bypasses key length validation, leading to out-of-bounds array reads.\",\"locations\":[{\"code_snippet\":\"\\tkey_idx = (keys.enckeylen >> 3) - 2;\\n\\tif (key_idx >= 3)\\n\\t\\treturn -EINVAL;\\n\\n...\\n\\tad->mci_enc = mci_cbc_enc_no_iv_array[key_idx];\\n\\tad->mci_dec = mci_cbc_dec_no_iv_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1741,\"why_this_location_matters\":\"This is where the missing lower bounds check allows a negative index to be evaluated and subsequently used for array lookups.\"},{\"code_snippet\":\"ad->mci_enc = mci_cbc_enc_no_iv_array[key_idx];\\n\\tad->mci_dec = mci_cbc_dec_no_iv_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1750,\"why_this_location_matters\":\"Uses the negative index, causing an out-of-bounds read from the adjacent static array.\"},{\"code_snippet\":\"int key_idx = (keylen >> 3) - 2;\\n\\nif (key_idx >= 3)\\n\\treturn -EINVAL;\\n\\nad.mci_enc = mci_cbc_enc_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cbc_setkey\",\"line\":955,\"why_this_location_matters\":\"The bounds check uses a signed comparison which fails to catch small key lengths, immediately followed by the out-of-bounds access.\"},{\"code_snippet\":\"int key_idx = (keylen >> 3) - 2;\\n\\nif (key_idx >= 3)\\n\\treturn -EINVAL;\\n\\nad.mci_enc = mci_ecb_enc_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_ecb_setkey\",\"line\":975,\"why_this_location_matters\":\"The bounds check uses a signed comparison which fails to catch small key lengths, immediately followed by the out-of-bounds access.\"},{\"code_snippet\":\"int key_idx;\\n... \\nkey_idx = (keys.enckeylen >> 3) - 2;\\nif (key_idx >= 3)\\n\\treturn -EINVAL;\\n...\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1785,\"why_this_location_matters\":\"This is where the signed comparison fails to catch small key lengths, allowing negative indices.\"}],\"patch_index\":4,\"patch_subject\":\"[PATCH 04/30] crypto: sa2ul - remove unused fields from sa_cmdl_cfg\",\"preexisting\":true,\"reasoning\":\"1. In key setting functions (`sa_aead_setkey`, `sa_aes_cbc_setkey`, `sa_aes_ecb_setkey`), the driver extracts or receives user-supplied key lengths.\\n2. The code computes an array index: `key_idx = (keylen >> 3) - 2`. If the key length is smaller than 16 bytes (e.g., 8 bytes), this results in a negative integer (e.g., -1).\\n3. Because `key_idx` is declared as a signed `int`, the subsequent upper bound check `if (key_idx >= 3)` evaluates to false for negative values, bypassing the validation entirely.\\n4. The driver then uses this negative index to read from static arrays like `mci_cbc_enc_no_iv_array[key_idx]`, causing an out-of-bounds kernel memory read before failing later in the software fallback or downstream functions.\",\"type\":\"Logic Error / Out-of-bounds Read\"},{\"description\":\"Stack buffer overflow in prepare_kipad() and prepare_kopad() during AEAD setkey.\",\"locations\":[{\"code_snippet\":\"if (sa_init_sc(&ctx->enc, ctx->dev_data->match_data, keys.enckey,\\n\\t\\t       keys.enckeylen, keys.authkey, keys.authkeylen,\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1763,\"why_this_location_matters\":\"Passes the unvalidated authkeylen into the initialization functions.\"},{\"code_snippet\":\"u8 k_pad[SHA1_BLOCK_SIZE];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":433,\"why_this_location_matters\":\"The fixed-size stack buffer being overflowed.\"},{\"code_snippet\":\"for (i = 0; i < key_sz; i++)\\n\\t\\tk_ipad[i] = key[i] ^ 0x36;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"prepare_kipad\",\"line\":377,\"why_this_location_matters\":\"Writes into the stack buffer out-of-bounds.\"}],\"patch_index\":4,\"patch_subject\":\"[PATCH 04/30] crypto: sa2ul - remove unused fields from sa_cmdl_cfg\",\"preexisting\":true,\"reasoning\":\"1. In `sa_aead_setkey()`, the user-provided key is parsed using `crypto_authenc_extractkeys()`, which sets `keys.authkeylen` based on the payload size. There is no check to ensure `keys.authkeylen` is within safe limits for HMAC.\\n2. This unbounded `authkeylen` is passed as `key_sz` to `sa_init_sc() -> sa_set_sc_auth() -> sa_prepare_iopads()`.\\n3. In `sa_prepare_iopads()`, a 64-byte stack buffer (`sha.k_pad`) is allocated.\\n4. `prepare_kipad()` and `prepare_kopad()` use the unbounded `key_sz` in a `for` loop, writing `key_sz` bytes into the 64-byte `k_pad` buffer.\\n5. Providing a large `authkey` via the `AF_ALG` socket interface results in a severe stack buffer overflow, leading to potential local privilege escalation or arbitrary code execution.\",\"type\":\"Buffer Overflow\"},{\"description\":\"Memory leaks in cra_init error paths.\",\"locations\":[{\"code_snippet\":\"if (IS_ERR(child)) {\\n\\t\\tdev_err(sa_k3_dev, \\\"Error allocating fallback algo %s\\\\n\\\", name);\\n\\t\\treturn PTR_ERR(child);\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":836,\"why_this_location_matters\":\"Leaks both `ctx->enc` and `ctx->dec` on failure.\"},{\"code_snippet\":\"if (IS_ERR(ctx->fallback.aead)) {\\n\\t\\tdev_err(sa_k3_dev, \\\"fallback driver %s couldn't be loaded\\\\n\\\",\\n\\t\\t\\tfallback);\\n\\t\\treturn PTR_ERR(ctx->fallback.aead);\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1675,\"why_this_location_matters\":\"Leaks previously allocated `ctx->shash`.\"},{\"code_snippet\":\"ret = sa_init_ctx_info(&ctx->dec, data);\\n\\tif (ret) {\\n\\t\\tsa_free_ctx_info(&ctx->enc, data);\\n\\t\\treturn ret;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1686,\"why_this_location_matters\":\"Leaks `ctx->shash` and `ctx->fallback.aead` when context initialization fails.\"}],\"patch_index\":4,\"patch_subject\":\"[PATCH 04/30] crypto: sa2ul - remove unused fields from sa_cmdl_cfg\",\"preexisting\":true,\"reasoning\":\"1. In initialization functions like `sa_cipher_cra_init()`, `sa_sha_cra_init_alg()`, and `sa_cra_init_aead()`, hardware context memory (`ctx->enc`, `ctx->dec`) is allocated from a DMA pool via `sa_init_ctx_info()`.\\n2. In the same functions, fallback algorithms are also allocated.\\n3. If an error occurs (such as failing to allocate a fallback tfm or initialize context info), the functions return an error pointer directly without freeing the DMA context memory or previously allocated fallbacks.\\n4. The Linux crypto API does not call `cra_exit()` when `cra_init()` fails, resulting in a persistent memory leak that can be triggered by unprivileged users requesting unsupported algorithm instances.\",\"type\":\"Memory Leak\"},{\"description\":\"The driver frees security context memory to the DMA pool without zeroizing the stored key material, violating the requirement that keys must be zeroized after use.\",\"locations\":[{\"code_snippet\":\"\\tif (ctx->sc) {\\n\\t\\tdma_pool_free(data->sc_pool, ctx->sc, ctx->sc_phys);\\n\\t\\tctx->sc = NULL;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":798,\"why_this_location_matters\":\"This is where the security context memory containing key material is returned to the DMA pool without being explicitly zeroized via memzero_explicit().\"}],\"patch_index\":4,\"patch_subject\":\"[PATCH 04/30] crypto: sa2ul - remove unused fields from sa_cmdl_cfg\",\"preexisting\":true,\"reasoning\":\"1. During key setup (`sa_init_sc`), the driver copies plaintext encryption keys and derived authentication key material (ipad/opad) into the DMA-mapped buffer `ctx->sc`.\\n2. When the crypto transform is destroyed, `sa_free_ctx_info()` returns `ctx->sc` to the DMA pool using `dma_pool_free()`.\\n3. The driver never explicitly zeroizes this buffer before freeing it, meaning sensitive master or derived keys remain exposed in the memory pool.\",\"type\":\"Missing Key Zeroization\"}],\"concerns_count\":6,\"dismissed_concerns\":[{\"description\":\"Removal of `akey` and `akey_len` from `sa_cmdl_cfg` might break authentication key setup or hardware command label generation.\",\"locations\":[{\"code_snippet\":\"static int sa_format_cmdl_gen(struct sa_cmdl_cfg *cfg, u8 *cmdl,\\n\\t\\t\\t      struct sa_cmdl_upd_info *upd_info)\\n{\\n\\tu8 enc_offset = 0, auth_offset = 0, total = 0;\\n\\tu8 enc_next_eng = SA_ENG_ID_OUTPORT2;\\n\\tu8 auth_next_eng = SA_ENG_ID_OUTPORT2;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":543,\"why_this_location_matters\":\"This is the primary function consuming `struct sa_cmdl_cfg` and it verifies that command label generation operates exclusively on control variables, not key material.\"},{\"code_snippet\":\"static int sa_format_cmdl_gen(struct sa_cmdl_cfg *cfg, u8 *cmdl,\\n\\t\\t\\t      struct sa_cmdl_upd_info *upd_info)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":566,\"why_this_location_matters\":\"This function is the sole consumer of `sa_cmdl_cfg` and clearly does not reference the removed fields.\"},{\"code_snippet\":\"\\t/* Setup Encryption Security Context & Command label template */\\n\\tif (sa_init_sc(&ctx->enc, ctx->dev_data->match_data, keys.enckey,\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1758,\"why_this_location_matters\":\"This shows the authentic keys are still safely and independently routed into the hardware state (`sa_init_sc`) regardless of the Command Label configuration.\"}],\"reasoning\":\"Investigation confirms that these fields in `sa_cmdl_cfg` were assigned but never read. The `sa_format_cmdl_gen()` function only requires engine IDs, encryption direction, and IV size to build the command descriptors. The actual cryptographic key data is passed securely and independently to the hardware Security Context (`sc_buf`) via `sa_init_sc()` -> `sa_set_sc_auth()`. The removal of these fields removes genuinely dead code and does not alter runtime behavior.\",\"type\":\"Logic Error / Missing Functionality\"},{\"description\":\"Removal of `akey` and `akey_len` could shift struct alignment or padding, potentially causing layout mismatches when passed to hardware.\",\"locations\":[{\"code_snippet\":\"static int sa_format_cmdl_gen(struct sa_cmdl_cfg *cfg, u8 *cmdl, ...)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":566,\"why_this_location_matters\":\"This function manually unpacks the fields instead of doing a memory copy, proving structural layout does not map to hardware memory constraints.\"}],\"reasoning\":\"The `sa_cmdl_cfg` struct is strictly used internally as a temporary configuration object on the stack. It is zero-initialized and its individual scalar fields are read explicitly by `sa_format_cmdl_gen` to construct the hardware command buffer `cmdl`. The struct memory itself is never block-copied to hardware or used in external APIs, making any layout or padding changes completely benign.\",\"type\":\"Struct Field Padding\"},{\"description\":\"Potential buffer overflow in sa_format_cmdl_gen() due to unbounded iv_size.\",\"locations\":[{\"code_snippet\":\"if (cfg->iv_size)\\n\\t\\t\\t\\tauth_offset += cfg->iv_size;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":563,\"why_this_location_matters\":\"Offset calculation that would trigger an out-of-bounds write if iv_size were unconstrained, but is safe because it is statically bounded.\"}],\"reasoning\":\"While the function `sa_format_cmdl_gen()` builds a command descriptor by iteratively adding lengths to offsets, `cfg->iv_size` is populated directly via `crypto_aead_ivsize()` and `crypto_skcipher_ivsize()`. These functions return fixed, static, constant values initialized by the kernel (e.g., 16 for AES). The `iv_size` is not user-controlled, so no overflow is possible on this path.\",\"type\":\"Buffer Overflow\"}],\"dismissed_concerns_count\":3,\"findings\":[]}","patch_id":189864,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":3668419,"tokens_in":4374895,"tokens_out":21174},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167760,"inline_review":"commit afeac784513c4757258d6b28be3b28e81d44bd09\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - remove unused fields from sa_tfm_ctx\n\nDead assignment. Remove it.\n\n> diff --git a/drivers/crypto/sa2ul.h b/drivers/crypto/sa2ul.h\n> index 097a496067e14..f29e0b9ac82f8 100644\n> --- a/drivers/crypto/sa2ul.h\n> +++ b/drivers/crypto/sa2ul.h\n> @@ -293,8 +293,6 @@ struct sa_tfm_ctx {\n>  \tstruct sa_ctx_info dec;\n>  \tint keylen;\n>  \tint iv_idx;\n> -\tu32 key[AES_KEYSIZE_256 / sizeof(u32)];\n\n[Severity: Low]\nDoes this removal leave a stale kernel-doc comment behind for the key field?\n\nLooking at the kernel-doc for struct sa_tfm_ctx:\n\n/**\n * struct sa_tfm_ctx: TFM context structure\n * @dev_data: struct sa_crypto_data pointer\n * @enc: struct sa_ctx_info for encryption\n * @dec: struct sa_ctx_info for decryption\n * @keylen: encrption/decryption keylength\n * @iv_idx: Initialization vector index\n * @key: encryption key\n * @fallback: SW fallback algorithm\n */\n\nIt appears the @key description was not removed alongside the field, which will\ncause a kernel-doc warning about an excess struct member description when\nbuilding with W=1 or running the kernel-doc script.\n\n> -\tu8 authkey[SHA512_BLOCK_SIZE];\n>  \tstruct crypto_shash\t*shash;\n>  \t/* for fallback */\n>  \tunion {","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Unbounded copy of user-supplied authentication key causes a stack buffer overflow in `prepare_kipad` and `prepare_kopad`.\",\"locations\":[{\"code_snippet\":\"\\tfor (i = 0; i < key_sz; i++)\\n\\t\\tk_ipad[i] = key[i] ^ 0x36;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"prepare_kipad\",\"line\":377,\"why_this_location_matters\":\"The loop condition relies on the unchecked user-supplied `key_sz`, overflowing the fixed 64-byte `k_pad` buffer passed into `k_ipad`.\"},{\"code_snippet\":\"\\tif (sa_init_sc(&ctx->enc, ctx->dev_data->match_data, keys.enckey,\\n\\t\\t       keys.enckeylen, keys.authkey, keys.authkeylen,\\n\\t\\t       ad, 1, &ctx->enc.epib[1]))\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1761,\"why_this_location_matters\":\"This is where the unbounded `keys.authkeylen` is passed down the call chain without checking if it exceeds `SHA1_BLOCK_SIZE`.\"}],\"patch_index\":5,\"patch_subject\":\"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx\",\"preexisting\":true,\"reasoning\":\"1. In `sa_aead_setkey()`, `crypto_authenc_extractkeys()` is called to extract `keys.authkeylen` and `keys.enckeylen`. The `authkeylen` can be arbitrarily large since `crypto_authenc_extractkeys()` only parses the header and does not enforce a maximum key length.\\n2. `sa_aead_setkey()` passes the raw `keys.authkeylen` unmodified as `authkey_sz` via `sa_init_sc()` -> `sa_set_sc_auth()` -> `ad->prep_iopad()` (which resolves to `sa_prepare_iopads()`).\\n3. `sa_prepare_iopads()` allocates a 64-byte stack buffer `u8 k_pad[SHA1_BLOCK_SIZE];` and calls `prepare_kipad(sha.k_pad, key, key_sz)`.\\n4. `prepare_kipad()` blindly loops `for (i = 0; i < key_sz; i++) k_ipad[i] = key[i] ^ 0x36;`, allowing an out-of-bounds write up to `key_sz` bytes on the stack frame, leading to critical memory corruption.\",\"type\":\"Stack Buffer Overflow\"},{\"description\":\"Missing validation on `enckeylen` causes a negative index out-of-bounds read in `sa_aead_setkey()`.\",\"locations\":[{\"code_snippet\":\"\\tkey_idx = (keys.enckeylen >> 3) - 2;\\n\\tif (key_idx >= 3)\\n\\t\\treturn -EINVAL;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1739,\"why_this_location_matters\":\"The signed comparison fails to prevent negative indices when `enckeylen` < 16.\"},{\"code_snippet\":\"\\tad->mci_enc = mci_cbc_enc_no_iv_array[key_idx];\\n\\tad->mci_dec = mci_cbc_dec_no_iv_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1748,\"why_this_location_matters\":\"The out-of-bounds read occurs here, loading uncontrolled memory into `ad->mci_enc` and `ad->mci_dec`.\"}],\"patch_index\":5,\"patch_subject\":\"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx\",\"preexisting\":true,\"reasoning\":\"1. `sa_aead_setkey()` calls `crypto_authenc_extractkeys()` to extract `keys.enckeylen`. A user can craft an input where `enckeylen` is less than 16 (e.g., 8 or 0).\\n2. The code computes the array index as `int key_idx = (keys.enckeylen >> 3) - 2;`. If `enckeylen` is 8, `key_idx` evaluates to `-1`.\\n3. The bounds check `if (key_idx >= 3)` does not catch negative values because `key_idx` is a signed integer.\\n4. The driver then accesses `mci_cbc_enc_no_iv_array[key_idx]`, resulting in an out-of-bounds array read with a negative index. (Note: `sa_aes_cbc_setkey()` shares this logic but is protected by `min_keysize = AES_MIN_KEY_SIZE` at the skcipher algorithm registration. AEAD algorithms do not have a framework-enforced `min_keysize`, making `sa_aead_setkey()` actively exploitable.)\",\"type\":\"Out-of-bounds Read\"},{\"description\":\"The return values of `sa_sha_cra_init_alg()` and `sa_sha_setup()` are completely ignored in `sa_sha1_cra_init`, `sa_sha256_cra_init`, and `sa_sha512_cra_init`, leading to deferred NULL pointer or ERR_PTR dereferences.\",\"locations\":[{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\\n\\nad.hash_size = SHA1_DIGEST_SIZE;\\nad.auth_ctrl = SA_AUTH_SW_CTRL_SHA1;\\n\\nsa_sha_setup(ctx, &ad);\\n\\nreturn 0;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1555,\"why_this_location_matters\":\"This is where initialization errors are swallowed, causing the driver to operate on an uninitialized context.\"},{\"code_snippet\":\"struct ahash_request *subreq = &rctx->fallback_req;\\nint ret;\\n\\nahash_request_set_tfm(subreq, ctx->fallback.ahash);\\n...\\nret = crypto_ahash_digest(subreq);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_run\",\"line\":1381,\"why_this_location_matters\":\"This fallback path dereferences the `NULL` or `ERR_PTR` fallback TFM if the initial allocation failed, causing the panic.\"},{\"code_snippet\":\"crypto_free_shash(ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_exit\",\"line\":1612,\"why_this_location_matters\":\"If initialization silently failed, this will dereference an ERR_PTR and crash the kernel.\"},{\"code_snippet\":\"memzero_explicit(sc_buf, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":694,\"why_this_location_matters\":\"This is where the actual NULL pointer dereference occurs because `sc_buf` (`ctx->sc`) is NULL when `sa_init_ctx_info()` previously failed.\"}],\"patch_index\":5,\"patch_subject\":\"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx\",\"preexisting\":true,\"reasoning\":\"1. Initialization functions like `sa_sha1_cra_init` call `sa_sha_cra_init_alg()` and `sa_sha_setup()` but completely ignore their return values, unconditionally returning 0 (success).\\n2. If `sa_sha_cra_init_alg` fails (e.g., `crypto_alloc_shash` or DMA pool allocation fails), it returns an error code, leaving `ctx->shash` and `ctx->fallback.ahash` as NULL or `ERR_PTR`.\\n3. Because success is falsely reported, the crypto framework may later invoke transformations or teardown.\\n4. If a hash operation runs, the fallback path (`sa_sha_run`) may dereference the NULL/ERR_PTR `ctx->fallback.ahash`, causing a local DoS. Similarly, `sa_init_sc()` could execute after failure, dereferencing a NULL `ctx->sc`.\\n5. During teardown, `sa_sha_cra_exit()` calls `crypto_free_shash(ctx->shash)` on the `ERR_PTR`, causing a panic.\\n6. The target patch makes this vulnerability more robustly reachable by removing an eager crash on `crypto_shash_blocksize(ctx->shash)` that previously halted execution immediately upon failure, effectively masking the early warning sign of the bug.\",\"type\":\"Missing Error Handling / Invalid Pointer Dereference\"},{\"description\":\"The patch aims to remove unused fields from `struct sa_tfm_ctx` but misses the `keylen` field, which is entirely unused.\",\"locations\":[{\"code_snippet\":\"\\tint keylen;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_tfm_ctx\",\"line\":311,\"why_this_location_matters\":\"This field is dead code and should have been removed along with `key` and `authkey`.\"}],\"patch_index\":5,\"patch_subject\":\"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx\",\"preexisting\":true,\"reasoning\":\"1. The commit message states it is removing dead assignments and unused fields from `sa_tfm_ctx`.\\n2. While `key` and `authkey` are removed, the `keylen` field is left intact.\\n3. A search across the driver confirms that `ctx->keylen` is never assigned to or read by any code, rendering it dead code.\",\"type\":\"Incomplete Cleanup\"},{\"description\":\"Multiple memory leaks exist in the driver's `.cra_init` implementations on error paths.\",\"locations\":[{\"code_snippet\":\"if (IS_ERR(child)) {\\n\\t\\tdev_err(sa_k3_dev, \\\"Error allocating fallback algo %s\\\\n\\\", name);\\n\\t\\treturn PTR_ERR(child);\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":841,\"why_this_location_matters\":\"This error path fails to free `ctx->enc` and `ctx->dec`.\"},{\"code_snippet\":\"if (IS_ERR(ctx->shash)) {\\n\\t\\t\\tdev_err(sa_k3_dev, \\\"base driver %s couldn't be loaded\\\\n\\\",\\n\\t\\t\\t\\talg_base);\\n\\t\\t\\treturn PTR_ERR(ctx->shash);\\n\\t\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1451,\"why_this_location_matters\":\"This error path fails to free the already allocated `ctx->enc`.\"},{\"code_snippet\":\"ret = sa_init_ctx_info(&ctx->enc, data);\\n\\tif (ret)\\n\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1684,\"why_this_location_matters\":\"This error path fails to free `ctx->shash` and `ctx->fallback.aead`.\"}],\"patch_index\":5,\"patch_subject\":\"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx\",\"preexisting\":true,\"reasoning\":\"1. In `sa_sha_cra_init_alg`: If `crypto_alloc_ahash` or `crypto_alloc_shash` fails, the function returns an error without freeing the previously allocated `ctx->shash` or DMA context (`ctx->enc`).\\n2. In `sa_cipher_cra_init`: If `crypto_alloc_skcipher` fails, the function returns without freeing `ctx->enc` and `ctx->dec` (allocated via `sa_init_ctx_info`).\\n3. In `sa_cra_init_aead`: If `sa_init_ctx_info(&ctx->enc, data)` or `sa_init_ctx_info(&ctx->dec, data)` fails, the function returns without freeing the previously allocated `ctx->shash` and `ctx->fallback.aead`.\\nThese leaks lead to resource exhaustion if crypto transformations fail to initialize.\",\"type\":\"Memory Leak\"}],\"concerns_count\":11,\"dismissed_concerns\":[{\"description\":\"Removing the `key` and `authkey` fields from `struct sa_tfm_ctx`, along with their initialization/`memset`, might break struct layout dependencies, hardware DMA expectations, or key configuration routines.\",\"locations\":[{\"code_snippet\":\"- u32 key[AES_KEYSIZE_256 / sizeof(u32)];\\n- u8 authkey[SHA512_BLOCK_SIZE];\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_tfm_ctx\",\"line\":296,\"why_this_location_matters\":\"This struct modification shrinks the context object safely since the fields are truly dead.\"},{\"code_snippet\":\"ctx->sc = dma_pool_alloc(data->sc_pool, GFP_KERNEL, &ctx->sc_phys);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":782,\"why_this_location_matters\":\"This proves that the actual hardware context memory is allocated completely independently of the struct layout.\"},{\"code_snippet\":\"-\\tint bs = crypto_shash_blocksize(ctx->shash);\\n...\\n-\\tmemset(ctx->authkey, 0, bs);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_setup\",\"line\":1409,\"why_this_location_matters\":\"This block calculates `bs` only to zero an unused field, verifying that the operation had no functional impact and can be safely deleted.\"}],\"reasoning\":\"The variables `key` and `authkey` were completely unreferenced dead code across the driver. `struct sa_tfm_ctx` is entirely a software control structure allocated inline by the crypto framework based strictly on its size. The actual hardware DMA buffers are allocated out-of-line via `dma_pool_alloc()` independently of this structure's layout. In key configuration routines (e.g., `sa_cipher_setkey`), keys are parsed and copied directly into the engine's internal hardware layout buffer (`ctx->enc.sc`), not stored in `ctx->key`. Removing these fixed-size arrays correctly reduces the `cra_ctxsize` memory footprint without impacting DMA operations, shifting physical addresses, or violating any hardware expectations. Additionally, since the fields are removed, removing their `memset` initialization (and the unused `crypto_shash_blocksize()` call that only existed to provide a length for the `memset`) is perfectly safe.\",\"type\":\"Unintended Side Effects / Struct Layout / Memory Corruption\"}],\"dismissed_concerns_count\":1,\"findings\":[{\"locations\":[{\"code_snippet\":\" * @key: encryption key\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_tfm_ctx\",\"line\":288,\"why_this_location_matters\":\"This is the leftover kernel-doc line documenting the removed struct member.\"}],\"patch_index\":5,\"patch_subject\":\"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: leftover kernel-doc for removed struct member key\",\"severity\":\"Low\",\"severity_explanation\":\"1. The commit removes the `key` field from `struct sa_tfm_ctx` but fails to remove its corresponding kernel-doc `@key:` line. \\n2. This causes a kernel-doc warning about an excess struct member description when building with `W=1` or running the kernel-doc script. \\n3. There is no visible functional impact as it is purely a documentation mismatch.\"}]}","patch_id":189865,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":5063314,"tokens_in":6196953,"tokens_out":29872},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167757,"inline_review":"commit b944992a509daea056ca1c2249c56cf44df883ff\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - remove unused macro definitions\n\nThis commit removes unused macro definitions from the sa2ul driver.\n\n> Remove unused macro definitions for auth functions (SA_MK_U32_AUTH,\n> SA_AUTHSW_VALID, SA_AUTHSW_*, SA_AUTH_OP_*) and related constants.\n\n[Severity: Medium]\nDoes the commit message accurately describe the changes?\n\nThe patch actually removes SA_AUTH_SUBKEY_LEN from drivers/crypto/sa2ul.c\nand NKEY_SZ from drivers/crypto/sa2ul.h, but none of the macros listed\nin the commit message appear in the diff.\n\nCould the commit message be updated to match the actual macros being removed?","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":3,\"dismissed_concerns\":[{\"description\":\"Removing `SA_AUTH_SUBKEY_LEN` and `NKEY_SZ` could cause compilation errors if they are referenced elsewhere.\",\"locations\":[{\"code_snippet\":\"-#define SA_AUTH_SUBKEY_LEN\\t16\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"SA_AUTH_SUBKEY_LEN\",\"line\":45,\"why_this_location_matters\":\"This macro is successfully removed without breaking any existing references.\"}],\"reasoning\":\"A global search of the codebase at the baseline revision confirms that both `SA_AUTH_SUBKEY_LEN` and `NKEY_SZ` are entirely unused. Their removal is safe and will not break the build or alter functionality.\",\"type\":\"Build Breakage\"},{\"description\":\"Possible hardware failure or DMA mapping error due to the removal of `authkey` and `key` buffers from `struct sa_tfm_ctx`.\",\"locations\":[{\"code_snippet\":\"-\\tu32 key[AES_KEYSIZE_256 / sizeof(u32)];\\n-\\tu8 authkey[SHA512_BLOCK_SIZE];\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"sa_tfm_ctx\",\"line\":296,\"why_this_location_matters\":\"This is where the key buffers were removed from the driver's crypto context struct.\"},{\"code_snippet\":\"memcpy(&sc_buf[SC_ENC_KEY_OFFSET], key, key_sz);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_set_sc_enc\",\"line\":526,\"why_this_location_matters\":\"This verifies that key material is copied into the dynamically allocated DMA-safe security context rather than relying on the `sa_tfm_ctx` buffers.\"}],\"reasoning\":\"In many cryptographic drivers, key material stored in the transformation context is directly mapped for DMA by the hardware engine. Removing these arrays could theoretically break hardware processing if they were used. However, tracing `sa_init_sc()`, the sa2ul driver dynamically allocates a separate Security Context (SC) buffer via a DMA pool (`dma_pool_alloc(data->sc_pool)`). The key material is then copied into this DMA-safe buffer in `sa_set_sc_enc()` and `sa_set_sc_auth()` using `memcpy` or padding routines. The `authkey` and `key` arrays in `struct sa_tfm_ctx` were completely dead code, never DMA mapped, and their removal is safe.\",\"type\":\"Resource Management\"},{\"description\":\"Removal of `SA_CMDL_UPD_AUTH_IV` and `SA_CMDL_UPD_AUX_KEY` code from the fast path in `sa_update_cmdl()` could break packet formatting if these flags were used.\",\"locations\":[{\"code_snippet\":\"-\\t\\tif (upd_info->flags & SA_CMDL_UPD_AUTH_IV) {\\n-\\t\\t\\tsa_copy_iv((void *)&cmdl[upd_info->auth_iv.index],\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":649,\"why_this_location_matters\":\"This is the execution path where the flags were evaluated prior to the patch.\"}],\"reasoning\":\"The patch removes logic handling `SA_CMDL_UPD_AUTH_IV` and `SA_CMDL_UPD_AUX_KEY` from `sa_update_cmdl()`. If any setup function was actually setting these flags in `upd_info->flags`, packets would be formatted incorrectly. A thorough search of the codebase demonstrates that `SA_CMDL_UPD_AUTH_IV` and `SA_CMDL_UPD_AUX_KEY` were only defined as macros and evaluated in `sa_update_cmdl()`, but were never actively bitwise-ORed into `upd_info->flags` anywhere in the driver. Consequently, the removed branches were genuinely dead code.\",\"type\":\"Dead Code\"}],\"dismissed_concerns_count\":3,\"findings\":[{\"locations\":[{\"code_snippet\":\"-#define SA_AUTH_SUBKEY_LEN\\t16\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"SA_AUTH_SUBKEY_LEN\",\"line\":45,\"why_this_location_matters\":\"This is one of the actual macros being removed, despite not being mentioned in the commit message.\"},{\"code_snippet\":\"-#define NKEY_SZ\\t\\t\\t3\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"NKEY_SZ\",\"line\":49,\"why_this_location_matters\":\"This is the second macro actually being removed, which is also completely omitted from the commit message.\"}],\"patch_index\":6,\"patch_subject\":\"[PATCH 06/30] crypto: sa2ul - remove unused macro definitions\",\"preexisting\":false,\"problem\":\"crypto: commit message misrepresents removed macros due to AI hallucination\",\"severity\":\"Medium\",\"severity_explanation\":\"Consequence: The commit message claims to remove SA_MK_U32_AUTH, SA_AUTHSW_VALID, SA_AUTHSW_*, and SA_AUTH_OP_*, but none of these macros exist in the baseline codebase. The patch actually removes SA_AUTH_SUBKEY_LEN and NKEY_SZ without documenting their removal in the commit message. This meaningful code and commit message mismatch reduces auditability and maintainability (e.g., git blame/log will show misleading information). Triggering path: N/A (metadata/documentation issue). Reachability: N/A. As per the severity guidelines, a meaningful code and commit message mismatch is classified as Medium severity.\"}]}","patch_id":189866,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":1876737,"tokens_in":2385590,"tokens_out":11031},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167770,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Missing validation of pointer returned by dmaengine_desc_get_metadata_ptr before dereferencing.\",\"locations\":[{\"code_snippet\":\"mdptr = (u32 *)dmaengine_desc_get_metadata_ptr(tx_out, &pl, &ml);\\n\\nsa_prepare_tx_desc(mdptr, ...);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":null,\"why_this_location_matters\":\"The potentially invalid pointer is obtained and immediately passed to a function that blindly dereferences it.\"}],\"patch_index\":11,\"patch_subject\":\"[PATCH 11/30] crypto: sa2ul - remove unused line\",\"preexisting\":true,\"reasoning\":\"1. `dmaengine_desc_get_metadata_ptr` can return an error pointer (e.g., `ERR_PTR(-ENOTSUPP)`) or `NULL` if metadata is unsupported or not configured properly for the DMA channel.\\n2. In `sa_run`, this return value is directly cast to a pointer (`mdptr`) and passed to `sa_prepare_tx_desc` without using `IS_ERR()` or checking for `NULL`.\\n3. `sa_prepare_tx_desc` immediately dereferences `mdptr` in a loop, which will cause a kernel panic if the pointer is invalid.\",\"type\":\"Missing Error Check\"},{\"description\":\"Missing return value check for dmaengine_desc_set_metadata_len.\",\"locations\":[{\"code_snippet\":\"dmaengine_desc_set_metadata_len(tx_out, req->mdata_size);\\n\\ndmaengine_submit(tx_out);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1239,\"why_this_location_matters\":\"This is where the metadata length is applied and the error is silently ignored before submitting the transfer.\"}],\"patch_index\":11,\"patch_subject\":\"[PATCH 11/30] crypto: sa2ul - remove unused line\",\"preexisting\":true,\"reasoning\":\"1. `dmaengine_desc_set_metadata_len` can fail and return a negative error code (e.g., `-EINVAL` if the requested payload length exceeds maximum bounds configured for the DMA channel).\\n2. The driver completely ignores the return value.\\n3. If it fails, the DMA descriptor is blindly submitted via `dmaengine_submit(tx_out)` with potentially corrupt or uninitialized metadata configuration, leading to undefined hardware behavior or data corruption.\",\"type\":\"Missing Error Check\"},{\"description\":\"Leaked DMA descriptor when outgoing DMA preparation fails.\",\"locations\":[{\"code_snippet\":\"\\t\\tgoto err_cleanup;\\n\\t}\\n\\n\\t/*\\n\\t * Prepare metadata for DMA engine.\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1221,\"why_this_location_matters\":\"This is the error path where the function exits after `rxd->tx_in` has been prepared but before it is submitted.\"}],\"patch_index\":11,\"patch_subject\":\"[PATCH 11/30] crypto: sa2ul - remove unused line\",\"preexisting\":true,\"reasoning\":\"1. `sa_run()` prepares the incoming DMA descriptor `rxd->tx_in` using `dmaengine_prep_slave_sg()`.\\n2. It then prepares the outgoing DMA descriptor `tx_out` using `dmaengine_prep_slave_sg()`.\\n3. If `tx_out` preparation fails (returns NULL), the code jumps to `err_cleanup`.\\n4. `err_cleanup` calls `sa_free_sa_rx_data(rxd)` to clean up resources, but this function only unmaps scatterlists and frees `rxd`.\\n5. The successfully prepared `rxd->tx_in` descriptor is never submitted and never freed (e.g., via `dmaengine_desc_free()`), resulting in a resource leak of the DMA descriptor.\",\"type\":\"Resource Leak\"},{\"description\":\"Missing bounds check on the maximum metadata length returned by the DMA engine, risking a buffer overflow if the channel is misconfigured.\",\"locations\":[{\"code_snippet\":\"mdptr = (u32 *)dmaengine_desc_get_metadata_ptr(tx_out, &pl, &ml);\\n\\nsa_prepare_tx_desc(mdptr, (sa_ctx->cmdl_size + (SA_PSDATA_CTX_WORDS * sizeof(u32))), cmdl, sizeof(sa_ctx->epib), sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1236,\"why_this_location_matters\":\"This is where the driver receives the maximum buffer limit `ml` but blindly copies data into `mdptr` without validating it.\"}],\"patch_index\":11,\"patch_subject\":\"[PATCH 11/30] crypto: sa2ul - remove unused line\",\"preexisting\":true,\"reasoning\":\"1. dmaengine_desc_get_metadata_ptr() returns a pointer to the descriptor's metadata buffer and writes the maximum available buffer size into the local variable `ml`.\\n2. The driver completely ignores `ml` and unconditionally writes up to 64 bytes (`epiblen + 4 + pslen`) into `mdptr` via `sa_prepare_tx_desc()`.\\n3. If the underlying DMA channel (e.g., ti-k3-udma) allocates a metadata size smaller than this unconditionally copied amount, the copy will corrupt adjacent descriptor memory.\\n4. The removed dead store `ml = ...` obscured this lack of bounds checking.\",\"type\":\"Buffer Overflow\"},{\"description\":\"Request type data written to the command label is silently truncated from the DMA payload.\",\"locations\":[{\"code_snippet\":\"cmdl[sa_ctx->cmdl_size / sizeof(u32)] = req->type;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1222,\"why_this_location_matters\":\"This is where the request type is written into the array, which will ultimately be ignored by the hardware due to payload truncation.\"},{\"code_snippet\":\"dmaengine_desc_set_metadata_len(tx_out, req->mdata_size);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1240,\"why_this_location_matters\":\"This limits the DMA metadata payload length, actively excluding the `req->type` data from the final transaction.\"}],\"patch_index\":11,\"patch_subject\":\"[PATCH 11/30] crypto: sa2ul - remove unused line\",\"preexisting\":true,\"reasoning\":\"1. The driver sets `req->type` into the `cmdl` array exactly after the command label at index `sa_ctx->cmdl_size / sizeof(u32)`.\\n2. `sa_prepare_tx_desc()` dutifully copies this into the DMA metadata buffer because `pslen` includes 16 extra bytes beyond `cmdl_size`.\\n3. However, `dmaengine_desc_set_metadata_len()` restricts the active DMA payload strictly to `req->mdata_size` (e.g., 44 bytes for a cipher request). This size exactly covers the 16-byte EPIB, 4-byte padding, and only the `cmdl_size` (e.g., 24 bytes), causing the hardware to completely ignore the trailing 16 bytes that contain `req->type`.\\n4. As a result, writing `req->type` is either entirely useless dead code, or `req->mdata_size` is incorrectly undersized, causing the hardware to miss required protocol data.\",\"type\":\"Logic Error\"}],\"concerns_count\":5,\"dismissed_concerns\":[{\"description\":\"The removed assignment to `ml` might have been necessary to correctly configure the metadata payload length passed to the DMA engine.\",\"locations\":[{\"code_snippet\":\"-\\tml = sa_ctx->cmdl_size + (SA_PSDATA_CTX_WORDS * sizeof(u32));\\n \\tdmaengine_desc_set_metadata_len(tx_out, req->mdata_size);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1239,\"why_this_location_matters\":\"This is the line removed by the commit. Tracking dataflow shows `ml` was overwritten but never read, confirming it as a dead assignment.\"},{\"code_snippet\":\"dmaengine_desc_set_metadata_len(tx_out, req->mdata_size);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1282,\"why_this_location_matters\":\"This line proves that the payload length is properly pushed into the DMA engine using the standard kernel API and the correct `req->mdata_size`.\"}],\"reasoning\":\"The variable `ml` was declared as a local `size_t` and used as an output parameter to `dmaengine_desc_get_metadata_ptr()`, capturing the maximum available length. The removed line immediately overwrote `ml` with its own calculation (evaluating to the psdata length, e.g. `cmdl_size + 16`), but this overwritten value was never read again. The subsequent `dmaengine_desc_set_metadata_len()` call correctly uses `req->mdata_size`, which already contains the full pre-calculated valid payload length (e.g., 44 for cipher, 52 for AEAD). Thus, the `ml` assignment was a pure dead store and its removal does not impact the correct metadata configuration.\",\"type\":\"Dead Code Removal\"},{\"description\":\"Uninitialized stack memory from the `cmdl` array is read and written into the DMA descriptor metadata, potentially leaking kernel stack data to the hardware.\",\"locations\":[{\"code_snippet\":\"\\tu32 cmdl[SA_MAX_CMDL_WORDS];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1058,\"why_this_location_matters\":\"The stack array is declared here and only partially populated via memcpy before being passed to sa_prepare_tx_desc.\"},{\"code_snippet\":\"\\tfor (out = &mdptr[5], in = psdata, i = 0;\\n\\t     i < pslen / sizeof(u32); i++)\\n\\t\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1032,\"why_this_location_matters\":\"This loop reads the uninitialized tail of the `cmdl` array and writes it to the DMA hardware descriptor memory.\"}],\"reasoning\":\"In `sa_run()`, the `cmdl` array is allocated on the stack but only partially initialized (up to `sa_ctx->cmdl_size`). `sa_prepare_tx_desc()` then reads `pslen / sizeof(u32)` words from `cmdl`, which includes up to 12 bytes of uninitialized stack memory, writing them into the DMA metadata buffer (`mdptr`). However, this is not an information leak because `sa_run()` subsequently calls `dmaengine_desc_set_metadata_len()` using `req->mdata_size` (e.g., 52 for AEAD). The underlying `k3-udma` driver configures the hardware to transmit exactly this many bytes. For AEAD, transmitting 52 bytes equates to 16 bytes of EPIB and 36 bytes of PSDATA, which aligns perfectly with the initialized portion of the command label. The uninitialized bytes written to the tail of the metadata buffer are ignored by the DMA engine and never leave the kernel.\",\"type\":\"Information Leak / OOB Read\"},{\"description\":\"Potential buffer overflow when writing up to 68 bytes to the DMA metadata buffer (`mdptr`) while the declared payload size is smaller (e.g., 44 or 52 bytes).\",\"locations\":[{\"code_snippet\":\"\\tfor (out = &mdptr[5], in = psdata, i = 0;\\n\\t     i < pslen / sizeof(u32); i++)\\n\\t\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1032,\"why_this_location_matters\":\"This loop overflows the stated payload length (`mdata_size`) by copying the full `pslen` into the descriptor metadata.\"}],\"reasoning\":\"`sa_prepare_tx_desc()` writes up to 68 bytes (16 bytes EPIB + 4 bytes header + 48 bytes PSDATA context) into `mdptr`. The target `mdata_size` for AEAD operations is manually bounded to 52 bytes. However, this discrepancy does not result in a buffer overflow. The `k3-udma` driver provisions a fixed metadata buffer size per channel statically defined by PSIL maps (e.g., `PSIL_SA2UL` defines `psd_size = 64` in `k3-psil-j721e.c`). Combined with the 16-byte EPIB requirement, the total allocated metadata buffer size dynamically carved into the descriptor ring is 80 bytes. Since 68 bytes strictly falls within the 80 bytes physically allocated by the DMA engine for this channel, the write is safely bounded and no adjacent descriptor memory is corrupted.\",\"type\":\"Buffer Overflow\"}],\"dismissed_concerns_count\":3,\"findings\":[]}","patch_id":189867,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":4708888,"tokens_in":5651679,"tokens_out":18053},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167766,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Potential unaligned pointer dereference when reading the encryption IV.\",\"locations\":[{\"code_snippet\":\"\\t\\t\\tu32 *enc_iv = (u32 *)req->enc_iv;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":656,\"why_this_location_matters\":\"Casting the byte pointer to a 32-bit word pointer without alignment guarantees.\"},{\"code_snippet\":\"\\t\\t\\tfor (j = 0; i < upd_info->enc_iv.size; i += 4, j++) {\\n\\t\\t\\t\\tdata[j] = cpu_to_be32(*enc_iv);\\n\\t\\t\\t\\tenc_iv++;\\n\\t\\t\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":663,\"why_this_location_matters\":\"This loop dereferences the potentially unaligned pointer.\"}],\"patch_index\":1,\"patch_subject\":\"[PATCH 01/30] crypto: sa2ul - remove dead code\",\"preexisting\":true,\"reasoning\":\"1. In `sa_update_cmdl()`, `req->enc_iv` (a `u8 *` which originates from the crypto API request `req->iv`) is cast directly to a `u32 *` pointer.\\n2. The code iterates and performs a direct 32-bit dereference: `data[j] = cpu_to_be32(*enc_iv);`.\\n3. The algorithms registered by this driver (like `cbc(aes)`) do not set a `cra_alignmask`, so the crypto API does not guarantee that the caller-provided IV buffer is 4-byte aligned.\\n4. Dereferencing an unaligned pointer without the `get_unaligned` accessor violates kernel coding standards and can trigger alignment faults or undefined behavior. While the target hardware (ARM64) natively supports unaligned accesses, C compilers assume aligned pointers and can optimize using instructions that fault on unaligned addresses.\",\"type\":\"Unaligned Memory Access\"},{\"description\":\"Uninitialized kernel stack memory is leaked to the DMA metadata buffer in `sa_run`.\",\"locations\":[{\"code_snippet\":\"\\tu32 cmdl[SA_MAX_CMDL_WORDS];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1061,\"why_this_location_matters\":\"Uninitialized stack buffer allocation.\"},{\"code_snippet\":\"\\tsa_prepare_tx_desc(mdptr, (sa_ctx->cmdl_size + (SA_PSDATA_CTX_WORDS *\\n\\t\\t\\t\\t   sizeof(u32))), cmdl, sizeof(sa_ctx->epib),\\n\\t\\t\\t   sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1249,\"why_this_location_matters\":\"Calling the function that copies the data to DMA, passing a length larger than what was initialized.\"},{\"code_snippet\":\"\\tfor (out = &mdptr[5], in = psdata, i = 0;\\n\\t     i < pslen / sizeof(u32); i++)\\n\\t\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1056,\"why_this_location_matters\":\"The loop that performs the out-of-bounds read from the uninitialized portion of the stack array into the DMA buffer.\"}],\"patch_index\":1,\"patch_subject\":\"[PATCH 01/30] crypto: sa2ul - remove dead code\",\"preexisting\":true,\"reasoning\":\"1. In `sa_run()`, an uninitialized array `u32 cmdl[SA_MAX_CMDL_WORDS]` is allocated on the stack.\\n2. `memcpy(cmdl, sa_ctx->cmdl, sa_ctx->cmdl_size)` initializes the first `sa_ctx->cmdl_size` bytes (typically 16-32 bytes).\\n3. An additional word is written via `cmdl[sa_ctx->cmdl_size / sizeof(u32)] = req->type;`, initializing 4 more bytes.\\n4. `sa_prepare_tx_desc()` is called with `pslen` equal to `sa_ctx->cmdl_size + (SA_PSDATA_CTX_WORDS * sizeof(u32))` (where SA_PSDATA_CTX_WORDS is 4).\\n5. Inside `sa_prepare_tx_desc()`, it loops over `psdata` (which points to `cmdl`), reading `pslen / 4` words to copy them to the DMA buffer `mdptr`.\\n6. Since it copies `(cmdl_size / 4) + 4` words, but only `(cmdl_size / 4) + 1` words were actually initialized on the stack, it copies 3 uninitialized words (12 bytes) of kernel stack memory into the DMA metadata buffer sent to the hardware.\",\"type\":\"Information Leak\"}],\"concerns_count\":6,\"dismissed_concerns\":[{\"description\":\"Removal of SA_CMDL_UPD_AUTH_IV and SA_CMDL_UPD_AUX_KEY might break hardware authentication IV or auxiliary key configuration.\",\"locations\":[{\"code_snippet\":\"-\\t\\tif (upd_info->flags & SA_CMDL_UPD_AUTH_IV) {\\n-\\t\\t\\tsa_copy_iv((void *)&cmdl[upd_info->auth_iv.index],\\n-\\t\\t\\t\\t   req->auth_iv,\\n-\\t\\t\\t\\t   (upd_info->auth_iv.size > 8));\\n-\\t\\t}\\n-\\t\\tif (upd_info->flags & SA_CMDL_UPD_AUX_KEY) {\\n-\\t\\t\\tint offset = (req->auth_size & 0xF) ? 4 : 0;\\n-\\n-\\t\\t\\tmemcpy(&cmdl[upd_info->aux_key_info.index],\\n-\\t\\t\\t       &upd_info->aux_key[offset], 16);\\n-\\t\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":657,\"why_this_location_matters\":\"This proves the removed code was gated by flags that were never populated.\"}],\"reasoning\":\"A comprehensive search across the entire codebase confirms that the `SA_CMDL_UPD_AUTH_IV` and `SA_CMDL_UPD_AUX_KEY` flags were never actually set in the `upd_info->flags` by `sa_format_cmdl_gen` or any other function. Because the flags were never set under any circumstances, the removed block in `sa_update_cmdl` and `sa_copy_iv` was entirely unreachable dead code. Removing it is a safe cleanup that introduces no missing functionality.\",\"type\":\"Code Removal / Unused Feature\"},{\"description\":\"Variable `i` might not be reset between loops in `sa_update_cmdl`.\",\"locations\":[{\"code_snippet\":\"\\t\\t\\tfor (j = 0; i < upd_info->enc_iv.size; i += 4, j++) {\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":665,\"why_this_location_matters\":\"This is the only loop where `i` is utilized, ruling out a state carry-over bug.\"}],\"reasoning\":\"The variable `i` is initialized to 0 at the start of `sa_update_cmdl`. The loop `for (j = 0; i < upd_info->enc_iv.size; i += 4, j++)` uses it as a byte tracker. Since there are no other loops in the function that use `i` (either before or after), and the function is invoked anew for each execution (as an inline function), `i` is guaranteed to be 0 when this loop starts. It correctly serves its single purpose without state carry-over issues.\",\"type\":\"Variable State\"},{\"description\":\"Possible hardware ABI breakage by removing struct fields from `struct sa_cmdl_upd_info`.\",\"locations\":[{\"code_snippet\":\"struct sa_cmdl_upd_info {\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_cmdl_upd_info\",\"line\":246,\"why_this_location_matters\":\"This struct is purely a software helper and does not map to hardware registers directly.\"}],\"reasoning\":\"One might suspect that `struct sa_cmdl_upd_info` or `struct sa_req` must maintain their memory layout for hardware DMA or ABI compatibility, justifying leaving the dead fields in place. However, these are strictly internal software structures. The actual hardware command format is maintained in the `cmdl` array, which `sa_cmdl_upd_info` merely holds indices for. Thus, the dead fields can and should safely be removed.\",\"type\":\"Hardware ABI Compatibility\"},{\"description\":\"Potential unaligned access and incorrect endianness conversion in IV copy logic.\",\"locations\":[{\"code_snippet\":\"u32 *enc_iv = (u32 *)req->enc_iv;\\n\\n\\t\\t\\tfor (j = 0; i < upd_info->enc_iv.size; i += 4, j++) {\\n\\t\\t\\t\\tdata[j] = cpu_to_be32(*enc_iv);\\n\\t\\t\\t\\tenc_iv++;\\n\\t\\t\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":642,\"why_this_location_matters\":\"This is where the byte array IV is cast to `u32*` and endian-swapped before being written to the DMA descriptor.\"}],\"reasoning\":\"The driver casts the byte-array `req->enc_iv` to a `u32 *` and processes it via `cpu_to_be32(*enc_iv)`. At first glance, this risks an unaligned read trap and seemingly scrambles byte order. However, the K3 (ARM64) architecture natively handles unaligned 32-bit accesses. More importantly, analyzing the DMA RX path (`sa_aes_dma_in_callback`) proves the crypto hardware engine treats IVs as an array of big-endian 32-bit words. Reading the array as little-endian `u32` words and swapping them with `cpu_to_be32` perfectly formats the contiguous byte array into the big-endian representation expected by the DMA descriptor, so the current inline implementation is functionally correct for the target hardware.\",\"type\":\"Endianness / Unaligned Access\"}],\"dismissed_concerns_count\":4,\"findings\":[]}","patch_id":189868,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2815754,"tokens_in":3591795,"tokens_out":18582},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167758,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Incomplete cleanup of unused code: the patch removes several unused struct members but leaves behind related unused fields and macros.\",\"locations\":[{\"code_snippet\":\"#define SA_MAX_AUX_DATA_WORDS\\t8\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"SA_MAX_AUX_DATA_WORDS\",\"line\":226,\"why_this_location_matters\":\"This macro is orphaned after the removal of aux_key array.\"},{\"code_snippet\":\"\\tu16\\tsubmode;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_cmdl_upd_info\",\"line\":240,\"why_this_location_matters\":\"This field was never used in sa2ul.c and was missed by the cleanup.\"},{\"code_snippet\":\"\\tu16\\toffset;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_cmdl_param_info\",\"line\":220,\"why_this_location_matters\":\"This field inside sa_cmdl_param_info is never written or read in the driver.\"}],\"patch_index\":2,\"patch_subject\":\"[PATCH 02/30] crypto: sa2ul - remove totally unused structure fields\",\"preexisting\":true,\"reasoning\":\"1. The macro SA_MAX_AUX_DATA_WORDS is defined but becomes completely unused because the only array using it (aux_key) is removed by this patch.\\n2. The 'submode' field inside 'struct sa_cmdl_upd_info' is never accessed in the driver.\\n3. The 'offset' field inside 'struct sa_cmdl_param_info' is also completely unused (only 'index' and 'size' are used in sa2ul.c).\",\"type\":\"Dead Code\"},{\"description\":\"Memory leaks in crypto initialization functions on error paths.\",\"locations\":[{\"code_snippet\":\"\\t\\treturn PTR_ERR(child);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":838,\"why_this_location_matters\":\"Returns without calling sa_free_ctx_info() for ctx->enc and ctx->dec.\"},{\"code_snippet\":\"\\t\\treturn PTR_ERR(ctx->fallback.aead);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1694,\"why_this_location_matters\":\"Returns without freeing the previously allocated ctx->shash.\"},{\"code_snippet\":\"\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1702,\"why_this_location_matters\":\"Returns without freeing ctx->shash and ctx->fallback.aead.\"},{\"code_snippet\":\"\\t\\t\\treturn PTR_ERR(ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1477,\"why_this_location_matters\":\"Returns without freeing the previously allocated ctx->enc context.\"},{\"code_snippet\":\"\\t\\t\\treturn PTR_ERR(ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1485,\"why_this_location_matters\":\"Returns without freeing ctx->shash and ctx->enc.\"}],\"patch_index\":2,\"patch_subject\":\"[PATCH 02/30] crypto: sa2ul - remove totally unused structure fields\",\"preexisting\":true,\"reasoning\":\"1. In `sa_cipher_cra_init()`, if `crypto_alloc_skcipher()` fails, the function returns the error but leaks the DMA context info allocated via `sa_init_ctx_info()` for `ctx->enc` and `ctx->dec`.\\n2. In `sa_cra_init_aead()`, if `crypto_alloc_aead()` fails, it leaks `ctx->shash`. If subsequent `sa_init_ctx_info()` calls fail, it leaks both `ctx->shash` and `ctx->fallback.aead`.\\n3. Similarly, in `sa_sha_cra_init_alg()`, failure to allocate `ctx->shash` or `ctx->fallback.ahash` leaks `ctx->enc` and any successfully allocated hashes.\\nSince `cra_exit` is not called by the crypto core when `cra_init` fails, these resources must be explicitly freed in the error paths.\",\"type\":\"Memory Leak\"}],\"concerns_count\":2,\"dismissed_concerns\":[{\"description\":\"Modifying the layout and size of `struct sa_cmdl_upd_info` (which also shifts the memory offset of `epib` within `struct sa_ctx_info`) might break hardware DMA descriptors, cause unaligned accesses, or firmware ABIs.\",\"locations\":[{\"code_snippet\":\"\\tstruct sa_cmdl_upd_info cmdl_upd_info;\\n\\t/* Store Auxiliary data such as K2/K3 subkeys in AES-XCBC */\\n\\tu32\\t\\tepib[SA_DMA_NUM_EPIB_WORDS];\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_ctx_info\",\"line\":285,\"why_this_location_matters\":\"Shows that cmdl_upd_info is co-located with epib, but is only used by the CPU for bookkeeping.\"},{\"code_snippet\":\"\\tfor (out = mdptr, in = epib, i = 0; i < epiblen / sizeof(u32); i++)\\n\\t\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1072,\"why_this_location_matters\":\"This demonstrates that epib is explicitly copied via its pointer word-by-word, proving the struct layout shift has no impact on hardware interaction or padding expectations.\"},{\"code_snippet\":\"\\t\\tcmdl[upd_info->auth_offset.index] |=\\n\\t\\t\\tFIELD_PREP(SA_CMDL_SOP_BYPASS_LEN_MASK,\\n\\t\\t\\t\\t   req->auth_offset);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":null,\"why_this_location_matters\":\"This shows how the struct is purely used to track software indices into the command label array, rather than being mapped to hardware itself.\"}],\"reasoning\":\"Tracing the usage of these structures in `sa2ul.c` reveals they are strictly software-side bookkeeping objects. `struct sa_cmdl_upd_info` is only used by `sa_update_cmdl()` and `sa_format_cmdl_gen()` to compute indices for word-by-word updates to a local command label array (`cmdl`), and `epib` is explicitly copied word-by-word into the actual DMA descriptor metadata in `sa_prepare_tx_desc()`. These structs are never mapped to DMA or passed to hardware directly. Therefore, shrinking the size and changing padding introduces no alignment issues or hardware compatibility problems.\",\"type\":\"Hardware Interface Compatibility / Struct Layout\"},{\"description\":\"Removing fields like `auth_iv`, `aux_key_info`, and `aux_key` from `struct sa_cmdl_upd_info` could theoretically break the build, as they were previously referenced by `sa_update_cmdl()` in `drivers/crypto/sa2ul.c`.\",\"locations\":[{\"code_snippet\":\"-\\tstruct sa_cmdl_param_info\\tauth_iv;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_cmdl_upd_info\",\"line\":241,\"why_this_location_matters\":\"The patch completely drops the `auth_iv` field.\"},{\"code_snippet\":\"-\\t\\tif (upd_info->flags & SA_CMDL_UPD_AUTH_IV) {\\n-\\t\\t\\tsa_copy_iv((void *)&cmdl[upd_info->auth_iv.index],\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":673,\"why_this_location_matters\":\"This was the sole consumer of the field, and it was cleanly removed in the preceding commit, proving the struct field is genuinely orphaned.\"}],\"reasoning\":\"A review of the baseline code reveals that `sa_update_cmdl()` did use these fields. However, these branches were dead code guarded by flags (`SA_CMDL_UPD_AUTH_IV` and `SA_CMDL_UPD_AUX_KEY`) that were defined but never actually set anywhere in the codebase. The immediately preceding commit (`628086ab7ab34fc16ef11247d5935d0e9cf2adea`) cleanly scrubbed this dead code from `sa2ul.c`. By the time the current commit is applied, the structure fields are genuinely unreferenced, validating the commit message's claim and making the removal completely safe and immune to build failures.\",\"type\":\"Compilation Breakage\"},{\"description\":\"Removing `struct sa_ctx_info auth` from `struct sa_tfm_ctx` reduces its size. If any part of the driver hardcodes the allocation size, tries to access the removed struct implicitly, or leaks memory without it, it could lead to memory corruption or resource management issues.\",\"locations\":[{\"code_snippet\":\"\\tstruct sa_ctx_info dec;\\n-\\tstruct sa_ctx_info auth;\\n\\tint keylen;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_tfm_ctx\",\"line\":null,\"why_this_location_matters\":\"This shows the removal of the auth field.\"},{\"code_snippet\":\"\\t\\t\\t.base.cra_ctxsize\\t= sizeof(struct sa_tfm_ctx),\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_algs\",\"line\":1696,\"why_this_location_matters\":\"Proves that context allocations by the crypto subsystem automatically adapt to the new, smaller size of `struct sa_tfm_ctx`.\"}],\"reasoning\":\"The `auth` field inside `struct sa_tfm_ctx` was completely unused across the entire driver (no references exist in `sa2ul.c`). The driver uses a separate `u8 authkey` array for authentication keys, and the authentication security context is instead written directly to the generic security context buffer via `sa_set_sc_auth()`. Furthermore, context allocations by the crypto subsystem automatically adapt to the new, smaller size of `struct sa_tfm_ctx` because they dynamically use `sizeof(struct sa_tfm_ctx)` via the `.base.cra_ctxsize` field. Therefore, the removal correctly cleans up dead code without affecting behavior or bounds safety.\",\"type\":\"Memory Corruption / Resource Management\"},{\"description\":\"Possible memory leak of split scatterlists or unmapped SG tables on dma_map_sgtable or sg_split failures in sa_run.\",\"locations\":[{\"code_snippet\":\"err_cleanup:\\n\\tsa_free_sa_rx_data(rxd);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1269,\"why_this_location_matters\":\"This handles the teardown symmetry for all DMA and scatterlist setup errors during execution.\"},{\"code_snippet\":\"\\t\\tif (mapped_sg->mapped) {\\n\\t\\t\\tdma_unmap_sgtable(rxd->ddev, &mapped_sg->sgt,\\n\\t\\t\\t\\t\\t  mapped_sg->dir, 0);\\n\\t\\t\\tkfree(mapped_sg->split_sg);\\n\\t\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_sa_rx_data\",\"line\":999,\"why_this_location_matters\":\"This cleanup function proves that partial mappings and allocations are properly cleaned up upon error.\"}],\"reasoning\":\"Investigated whether the error cleanup path in sa_run correctly frees resources if partial mapping succeeds. The driver tracks successfully mapped scatterlists using `mapped_sg->mapped = true` and `mapped_sg->split_sg = src`. In the `err_cleanup` path, `sa_free_sa_rx_data()` iterates over the `rxd->mapped_sg` array. It correctly checks `if (mapped_sg->mapped)` before unmapping and freeing the split scatterlists via `kfree(mapped_sg->split_sg)`. Thus, no resources are leaked when `sa_run` aborts asynchronously.\",\"type\":\"Resource Management\"}],\"dismissed_concerns_count\":4,\"findings\":[]}","patch_id":189869,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":6402657,"tokens_in":7664369,"tokens_out":25286},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167759,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Negative array index and out-of-bounds read in AES key setup for AEAD algorithms.\",\"locations\":[{\"code_snippet\":\"\\tkey_idx = (keys.enckeylen >> 3) - 2;\\n\\tif (key_idx >= 3)\\n\\t\\treturn -EINVAL;\\n\\n...\\n\\tad->mci_enc = mci_cbc_enc_no_iv_array[key_idx];\\n\\tad->mci_dec = mci_cbc_dec_no_iv_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":1747,\"why_this_location_matters\":\"The key_idx calculation can result in a negative number, bypassing the >= 3 bounds check and leading to an out-of-bounds array read.\"}],\"patch_index\":3,\"patch_subject\":\"[PATCH 03/30] crypto: sa2ul - remove unused algorithm ID fields\",\"preexisting\":true,\"reasoning\":\"1. `sa_aead_setkey` is used to configure AEAD keys. The user-provided key blob is parsed by `crypto_authenc_extractkeys()`, which sets `keys.enckeylen` based on the arbitrary size specified in the RTA header.\\n2. The crypto AEAD core does not validate `keylen` against a `min_keysize` before calling the driver's `.setkey` callback.\\n3. The driver calculates `int key_idx = (keys.enckeylen >> 3) - 2;`.\\n4. If `keys.enckeylen` is less than 16 (e.g., 8), `keys.enckeylen >> 3` evaluates to 1. Because `keys.enckeylen` is unsigned, `1U - 2U` underflows to `0xFFFFFFFFU`, which is cast to `-1` when assigned to the signed `int key_idx`.\\n5. The bounds check `if (key_idx >= 3)` uses a signed comparison. Since `-1 >= 3` is false, it fails to reject the invalid length.\\n6. The code then reads from `mci_cbc_enc_no_iv_array[-1]` and `mci_cbc_dec_no_iv_array[-1]`, leading to an out-of-bounds memory access that is later copied into the hardware security context buffer.\",\"type\":\"Out-of-Bounds Read\"}],\"concerns_count\":1,\"dismissed_concerns\":[{\"description\":\"Removing fields from `struct sa_cmdl_cfg` and `struct algo_data` might alter memory layout, cause uninitialized memory, or break hardware command formatting.\",\"locations\":[{\"code_snippet\":\"static int sa_format_cmdl_gen(struct sa_cmdl_cfg *cfg, u8 *cmdl, struct sa_cmdl_upd_info *upd_info)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":566,\"why_this_location_matters\":\"This function builds the hardware command label from the cfg struct, confirming that the removed `aalg` field is never accessed or written to hardware.\"},{\"code_snippet\":\"int sa_init_sc(struct sa_ctx_info *ctx, const struct sa_match_data *match_data, const u8 *enc_key, u16 enc_key_sz, const u8 *auth_key, u16 auth_key_sz, struct algo_data *ad, u8 enc, u32 *swinfo)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":717,\"why_this_location_matters\":\"Formats the hardware Security Context (SC) buffer from the algo_data struct, proving that `aalg_id` and `ealg_id` are never used.\"},{\"code_snippet\":\"static void sa_set_sc_auth(struct algo_data *ad, const u8 *key, u16 key_sz,\\n\\t\\t\\t   u8 *sc_buf)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_set_sc_auth\",\"line\":532,\"why_this_location_matters\":\"Initializes the hardware context for authentication using `ad->auth_ctrl` to configure the algorithm, verifying that `ad->aalg_id` is indeed unused.\"},{\"code_snippet\":\"\\tmemset(&cfg, 0, sizeof(cfg));\\n-\\tcfg.aalg = ad->aalg_id;\\n \\tcfg.enc_eng_id = ad->enc_eng.eng_id;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_setup\",\"line\":1422,\"why_this_location_matters\":\"Demonstrates where the removed assignments occurred; the remaining struct zeroing guarantees safe initialization.\"},{\"code_snippet\":\"struct sa_cmdl_cfg cfg;\\n\\t// ...\\n\\tmemzero_explicit(&cfg, sizeof(cfg));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_setkey\",\"line\":862,\"why_this_location_matters\":\"Demonstrates that the configuration structure is purely a local stack variable, not a hardware-mapped descriptor.\"}],\"reasoning\":\"Both `struct sa_cmdl_cfg` and `struct algo_data` are purely driver-internal software abstractions allocated on the stack and safely zero-initialized via `memset` or `{ 0 }`. They are never directly passed to hardware or DMA mapped. Helpers like `sa_format_cmdl_gen()` and `sa_init_sc()` unpack individual fields to manually construct the actual hardware command labels and security context buffers. A rigorous check reveals that these helpers do not use `aalg` or `ealg_id`/`aalg_id`. Instead, the hardware context relies on engine IDs (`enc_eng_id`, `auth_eng_id`), mode control instructions (`mci_enc`, `mci_dec`), and software control flags (`auth_ctrl`). Thus, these algorithm ID fields were genuinely unused, and their removal correctly eliminates dead code without impacting the hardware interface, data structure layout, or causing uninitialized gaps.\",\"type\":\"Hardware ABI Compatibility and Configuration\"},{\"description\":\"Potential out-of-bounds array read with negative index in `sa_aes_cbc_setkey` and `sa_aes_ecb_setkey`.\",\"locations\":[{\"code_snippet\":\"\\tint key_idx = (keylen >> 3) - 2;\\n\\n\\tif (key_idx >= 3)\\n\\t\\treturn -EINVAL;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cbc_setkey\",\"line\":null,\"why_this_location_matters\":\"This logic appears vulnerable to underflow, but the crypto core's min_keysize enforcement prevents it from triggering here.\"}],\"reasoning\":\"While these functions use the exact same vulnerable logic (`int key_idx = (keylen >> 3) - 2; if (key_idx >= 3) ...`) as `sa_aead_setkey`, they are used exclusively for `skcipher` transformations. The `skcipher` crypto core API (`crypto_skcipher_setkey`) validates that `keylen` is within `[alg->min_keysize, alg->max_keysize]` before invoking the driver's callback. Since `AES_MIN_KEY_SIZE` is 16, `keylen` can never be less than 16, making a negative `key_idx` structurally impossible for these specific paths.\",\"type\":\"Out-of-Bounds Read\"}],\"dismissed_concerns_count\":2,\"findings\":[]}","patch_id":189870,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":1759905,"tokens_in":2243771,"tokens_out":11499},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167764,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Hardware crypto context memory containing sensitive keys is freed without being zeroized.\",\"locations\":[{\"code_snippet\":\"\\tif (ctx->sc) {\\n\\t\\tdma_pool_free(data->sc_pool, ctx->sc, ctx->sc_phys);\\n\\t\\tctx->sc = NULL;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":774,\"why_this_location_matters\":\"This is where the context memory containing derived key material is returned to the DMA pool without being wiped.\"}],\"patch_index\":7,\"patch_subject\":\"[PATCH 07/30] crypto: sa2ul - consolidate encryption offset definitions\",\"preexisting\":true,\"reasoning\":\"1. In `sa_set_sc_enc()` and `sa_set_sc_auth()`, encryption and authentication keys are written directly into the `sc_buf` memory (which is mapped from `ctx->sc`).\\n2. When the hardware context is torn down, `sa_free_ctx_info()` calls `dma_pool_free(data->sc_pool, ctx->sc, ctx->sc_phys)` to return the memory to the DMA pool.\\n3. The memory is not explicitly zeroized before freeing via `memzero_explicit()`. This leaves sensitive key material in memory until it gets re-allocated and overwritten, which violates the strict subsystem guideline 'Keys must be zeroized after use'.\",\"type\":\"Missing Key Zeroization\"},{\"description\":\"The patch updates array size declarations from MODE_CONTROL_BYTES to SC_ENC_MCI_SIZE but misses arrays that had a hardcoded literal 27.\",\"locations\":[{\"code_snippet\":\"static u8 mci_ecb_enc_array[3][27] = {\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"mci_ecb_enc_array\",\"line\":308,\"why_this_location_matters\":\"This array was skipped during the replacement and still relies on a magic number.\"},{\"code_snippet\":\"static u8 mci_ecb_dec_array[3][27] = {\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"mci_ecb_dec_array\",\"line\":324,\"why_this_location_matters\":\"This array also missed the replacement and uses a hardcoded 27.\"}],\"patch_index\":7,\"patch_subject\":\"[PATCH 07/30] crypto: sa2ul - consolidate encryption offset definitions\",\"preexisting\":true,\"reasoning\":\"1. The commit replaces the old MODE_CONTROL_BYTES macro with SC_ENC_MCI_SIZE for arrays like mci_cbc_enc_array, mci_cbc_enc_no_iv_array, and mci_cbc_3des_enc_array to fulfill the claim of consolidating encryption offset definitions.\\n2. However, mci_ecb_enc_array and mci_ecb_dec_array previously used a hardcoded size of 27 instead of the old macro, so they were missed during the replacement.\\n3. Although this does not introduce a functional bug or memory issue (since SC_ENC_MCI_SIZE evaluates to exactly 27), it results in an incomplete refactoring and leaves a maintainability trap if the MCI size ever needs to change.\",\"type\":\"Incomplete Refactoring\"}],\"concerns_count\":2,\"dismissed_concerns\":[{\"description\":\"Deletion of SA_CTX_ENC_AUX4_OFFSET and MCI_SZ from sa2ul.h without replacement could break dependencies.\",\"locations\":[{\"code_snippet\":\"-#define SA_CTX_ENC_AUX4_OFFSET  128\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"SA_CTX_ENC_AUX4_OFFSET\",\"line\":150,\"why_this_location_matters\":\"This is where the SA_CTX_ENC_AUX4_OFFSET macro was removed.\"},{\"code_snippet\":\"-#define MCI_SZ\\t\\t\\t27\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"MCI_SZ\",\"line\":49,\"why_this_location_matters\":\"Shows where the dead constant MCI_SZ was removed without issue.\"}],\"reasoning\":\"While other auxiliary offsets (like `SA_CTX_ENC_AUX2_OFFSET`) were logically translated, `SA_CTX_ENC_AUX4_OFFSET` (originally 128) and `MCI_SZ` (27) were completely removed. A full codebase search confirms that these constants were dead code strictly internal to the sa2ul subsystem and never referenced. Their removal without replacement does not cause Link-Time Optimization (LTO) issues, header conflicts, or undefined symbols.\",\"type\":\"Missing Macro Replacement\"},{\"description\":\"Possible incorrect calculation or bitwise clobbering when using the new SC_ENC_AUX2_OFFSET macro in sa_format_cmdl_gen().\",\"locations\":[{\"code_snippet\":\"\\t\\t\\tcmdl[enc_offset + SA_CMDL_OFFSET_OPTION_CTRL1] =\\n\\t\\t\\t\\t(SC_ENC_AUX2_OFFSET | (cfg->iv_size >> 3));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":600,\"why_this_location_matters\":\"This is the control register assignment where the newly consolidated offset macro interacts with shifting operations.\"}],\"reasoning\":\"In the baseline code, `SA_CTX_ENC_AUX2_OFFSET` was hardcoded to 96. The patch introduces `SC_ENC_AUX2_OFFSET` derived as `(SC_ENC_AUX1_OFFSET + SC_ENC_AUX1_SIZE)`. Tracing the chain: `SC_ENC_MODESEL_OFFSET (0) + SC_ENC_MODESEL_SIZE (1) = SC_ENC_MCI_OFFSET (1)`. Then `1 + SC_ENC_MCI_SIZE (27) + 4 = SC_ENC_KEY_OFFSET (32)`. Then `32 + SC_ENC_KEY_SIZE (32) = SC_ENC_AUX1_OFFSET (64)`. Finally `64 + SC_ENC_AUX1_SIZE (32)` evaluates exactly to 96. Because `SC_ENC_AUX2_OFFSET` identically matches the old value (96), the bitwise OR assignment `(SC_ENC_AUX2_OFFSET | (cfg->iv_size >> 3))` performs exactly the same as before, with no bitwise clobbering or functional changes.\",\"type\":\"Refactoring Error / Offset Miscalculation\"},{\"description\":\"Possible corruption of the hardware security context memory layout or buffer overflow due to calculated offset macros replacing hardcoded ones.\",\"locations\":[{\"code_snippet\":\"#define SC_ENC_KEY_OFFSET (SC_ENC_MCI_OFFSET + SC_ENC_MCI_SIZE + 4)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"SC_ENC_KEY_OFFSET\",\"line\":42,\"why_this_location_matters\":\"This macro explicitly preserves the 4 bytes of padding, ensuring the key offset remains identical (32) to the baseline.\"},{\"code_snippet\":\"memcpy(&sc_buf[SC_ENC_MCI_OFFSET], mci, SC_ENC_MCI_SIZE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_set_sc_enc\",\"line\":517,\"why_this_location_matters\":\"Proves the MCI offset and size correctly resolve to buffer offset 1 and length 27, identical to the baseline implementation.\"},{\"code_snippet\":\"memcpy(&sc_buf[SC_ENC_KEY_OFFSET], key, key_sz);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_set_sc_enc\",\"line\":526,\"why_this_location_matters\":\"This is where the key is written to the calculated offset in the security context buffer, proving the total write length is within safe bounds.\"}],\"reasoning\":\"The new macro definitions systematically calculate offsets instead of hardcoding them. Verification shows that the generated offsets evaluate to the exact same integers as the original code, explicitly preserving the 4-byte padding (`SC_ENC_KEY_OFFSET` evaluates to 32 bytes). The memory layout remains strictly identical. Furthermore, the buffer `sc_buf` is allocated using `SA_CTX_MAX_SZ` (256 bytes), which comfortably fits the maximum bounds written (offset 32 + 32 byte key size = 64 bytes). Therefore, writes are well within bounds and no boundary checks are bypassed.\",\"type\":\"Memory Layout Alteration / Buffer Overflow\"}],\"dismissed_concerns_count\":3,\"findings\":[]}","patch_id":189871,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2516646,"tokens_in":3231714,"tokens_out":13710},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167765,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The commit fixes a memory leak in the error path of `sa_cipher_cra_init()`, but misses identical memory leaks in `sa_cra_init_aead()` and `sa_sha_cra_init_alg()`.\",\"locations\":[{\"code_snippet\":\"\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1681,\"why_this_location_matters\":\"This error path fails to free the previously allocated `ctx->shash` and `ctx->fallback.aead`.\"},{\"code_snippet\":\"\\t\\t\\treturn PTR_ERR(ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1460,\"why_this_location_matters\":\"This error path returns directly without freeing the successfully initialized `ctx->enc` context.\"}],\"patch_index\":15,\"patch_subject\":\"[PATCH 15/30] crypto: sa2ul - fix context release on errors\",\"preexisting\":true,\"reasoning\":\"In `sa_cra_init_aead()`, `ctx->shash` and `ctx->fallback.aead` are allocated first. If subsequent calls to `sa_init_ctx_info()` fail, the function returns the error but fails to free these allocated resources. Similarly, if `crypto_alloc_aead()` fails, it returns without freeing `ctx->shash`. In `sa_sha_cra_init_alg()`, `sa_init_ctx_info(&ctx->enc, data)` is called first. If the subsequent `crypto_alloc_shash()` or `crypto_alloc_ahash()` fails, the function returns without calling `sa_free_ctx_info()` to clean up `ctx->enc`. Since the crypto framework destroys the algorithm tfm using `kfree()` without invoking `.cra_exit` when `.cra_init` fails, these allocations leak permanently.\",\"type\":\"Incomplete Fix / Memory Leaks\"},{\"description\":\"Wrapper functions like `sa_sha1_cra_init` ignore the return values of `sa_sha_cra_init_alg()` and `sa_sha_setup()`, leading to guaranteed NULL pointer dereferences and resource corruption.\",\"locations\":[{\"code_snippet\":\"\\tsa_sha_cra_init_alg(tfm, \\\"sha1\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1556,\"why_this_location_matters\":\"The caller ignores the integer return value of `sa_sha_cra_init_alg` and proceeds unconditionally on failure.\"},{\"code_snippet\":\"\\tsa_sha_setup(ctx, &ad);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1561,\"why_this_location_matters\":\"The return value of this setup function is also ignored, triggering a crash when dereferencing the failed context pointers.\"}],\"patch_index\":15,\"patch_subject\":\"[PATCH 15/30] crypto: sa2ul - fix context release on errors\",\"preexisting\":true,\"reasoning\":\"Functions like `sa_sha1_cra_init()` call `sa_sha_cra_init_alg()` but ignore its return value. If memory allocation inside `sa_sha_cra_init_alg()` fails (e.g., `-ENOMEM`), `ctx->enc.sc` remains `NULL`. The wrapper function then blindly proceeds to call `sa_sha_setup()`, passing the partially initialized context to `sa_init_sc()`. `sa_init_sc()` unconditionally executes `memzero_explicit(ctx->sc, SA_CTX_MAX_SZ);`. Since `ctx->sc` is `NULL`, this will cause a kernel panic. Additionally, because the wrapper unconditionally returns `0`, the crypto framework falsely assumes initialization succeeded.\",\"type\":\"Unhandled Error / NULL Pointer Dereference\"},{\"description\":\"Missing bounds check in `sa_init_ctx_info` leads to an out-of-bounds array write if all contexts are allocated, corrupting adjacent structure members.\",\"locations\":[{\"code_snippet\":\"\\tbn = find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX);\\n\\t__set_bit(bn, data->ctx_bm);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":775,\"why_this_location_matters\":\"This is where the out-of-bounds index is unconditionally used to set a bit, corrupting the adjacent structure field.\"}],\"patch_index\":15,\"patch_subject\":\"[PATCH 15/30] crypto: sa2ul - fix context release on errors\",\"preexisting\":true,\"reasoning\":\"`sa_init_ctx_info()` calls `find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX)`. If all 512 contexts are in use (e.g., heavily utilized by AF_ALG socket requests), this returns `SA_MAX_NUM_CTX` (512). The code immediately calls `__set_bit(bn, data->ctx_bm)` without checking if `bn >= SA_MAX_NUM_CTX`. Since `data->ctx_bm` is allocated for exactly 512 bits, setting bit 512 writes past the end of the array. This silently corrupts the struct member immediately following `ctx_bm` (`struct dma_chan *dma_rx1`), which will cause arbitrary memory corruption or kernel crashes during DMA operations.\",\"type\":\"Out-of-bounds Write\"}],\"concerns_count\":13,\"dismissed_concerns\":[{\"description\":\"Risk of double frees via `cra_exit` after an initialization error, or invalid frees from unconditional cleanup functions like `sa_exit_tfm_aead()`.\",\"locations\":[{\"code_snippet\":\"\\tsa_free_ctx_info(&ctx->enc, data);\\n\\tsa_free_ctx_info(&ctx->dec, data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_exit_tfm_aead\",\"line\":1715,\"why_this_location_matters\":\"This unconditional free only occurs because the framework guarantees successful initialization prior to calling exit.\"}],\"reasoning\":\"The Linux crypto API guarantees that a cipher's `cra_exit` (or `exit` callback) is ONLY called if its `cra_init` successfully completed and returned `0`. If `cra_init` fails, the framework cleans up the TFM struct itself via `kfree()` but does not invoke the algorithm's exit callback. Therefore, explicit cleanup within the `cra_init` error path is necessary and will not cause double-frees via `.exit`. Likewise, `sa_exit_tfm_aead()` will only ever execute on fully initialized contexts, making unconditional cleanup there safe.\",\"type\":\"Double Free or Invalid Free in Exit Path\"},{\"description\":\"Potential leak of `ctx->sc_id` and the associated allocated bit if `dma_pool_alloc` fails inside `sa_init_ctx_info`.\",\"locations\":[{\"code_snippet\":\"\\t__clear_bit(bn, data->ctx_bm);\\n\\tdata->sc_id--;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":792,\"why_this_location_matters\":\"Confirms the bit map allocation is cleanly rolled back on memory allocation failure.\"}],\"reasoning\":\"If `dma_pool_alloc` fails, `goto scid_rollback` is executed. The rollback path safely clears the bit using `__clear_bit(bn, data->ctx_bm)` and decrements `data->sc_id`, effectively reverting the resource claim cleanly without leaving behind a leak.\",\"type\":\"Memory Leak\"},{\"description\":\"Possible resource leak, double-free, or clearing of uninitialized context bits when `crypto_alloc_skcipher` or `sa_init_ctx_info` fails in `sa_cipher_cra_init`.\",\"locations\":[{\"code_snippet\":\"alloc_err:\\n\\tsa_free_ctx_info(&ctx->dec, data);\\nctx_dec_err:\\n\\tsa_free_ctx_info(&ctx->enc, data);\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":847,\"why_this_location_matters\":\"This correctly cleans up the contexts in LIFO order without risking operations on uninitialized data.\"}],\"reasoning\":\"The patch successfully handles this by adding cascaded error blocks (`alloc_err` and `ctx_dec_err`) that correctly chain `sa_free_ctx_info` calls in reverse allocation order. If `sa_init_ctx_info(&ctx->dec, ...)` fails, it rolls back its own internal state and jumps to `ctx_dec_err` which only frees the previously succeeded `ctx->enc`. The error paths strictly only call `sa_free_ctx_info` for contexts that have already successfully initialized, correctly handling cleanup without double freeing or clearing uninitialized bits.\",\"type\":\"Resource Management\"}],\"dismissed_concerns_count\":3,\"findings\":[]}","patch_id":189873,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":1696235,"tokens_in":2334645,"tokens_out":19501},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167756,"inline_review":"commit 3459d033955042b5debb6c6fab2b6aba5ba39b64\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - remove unused base register pointer\n\nThis commit removes the unused base register pointer from the sa_crypto_data\nstructure.\n\n> The driver uses the psilss_base pointer instead for all register\n> accesses.\n\n[Severity: Medium]\nIs this description accurate? The driver does not appear to use a psilss_base\npointer anywhere for register accesses.\n\nLooking at drivers/crypto/sa2ul.c:sa_ul_probe(), the driver uses the local\nvariable saul_base for register access, which is also what the removed code\nused:\n\ndrivers/crypto/sa2ul.c:sa_ul_probe() {\n    ...\n    saul_base = devm_platform_ioremap_resource(pdev, 0);\n    ...\n    dev_data->base = saul_base;\n    ...\n}\n\nCould the commit message be updated to correctly reflect the actual pointer\nused?","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The local variable `saul_base` in the probe function is declared as static, causing data races and state corruption if multiple devices are probed concurrently.\",\"locations\":[{\"code_snippet\":\"static void __iomem *saul_base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2325,\"why_this_location_matters\":\"This static declaration creates a shared global variable for a per-device memory mapping instead of being stack-local.\"},{\"code_snippet\":\"saul_base = devm_platform_ioremap_resource(pdev, 0);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2338,\"why_this_location_matters\":\"The shared static variable is unconditionally overwritten here, causing state corruption if multiple probes run concurrently.\"}],\"patch_index\":9,\"patch_subject\":\"[PATCH 09/30] crypto: sa2ul - remove unused base register pointer\",\"preexisting\":true,\"reasoning\":\"1. `saul_base` is defined as `static void __iomem *saul_base;` inside `sa_ul_probe()`.\\n2. During probe, it is assigned the memory-mapped I/O resource for the current device via `devm_platform_ioremap_resource()`.\\n3. Because it is static, it is shared across all concurrent invocations of the probe function.\\n4. If two devices probe concurrently, one instance could overwrite `saul_base` while the other is between the assignment and its subsequent use in `readl_relaxed()` / `writel_relaxed()`, causing the driver to read/write the wrong device's registers.\",\"type\":\"Concurrency / Data Race\"},{\"description\":\"The driver relies on a global variable `sa_k3_dev` to access device state, which breaks multi-instance support, leaves dangling pointers on probe failure, and causes NULL pointer dereferences on driver unbind.\",\"locations\":[{\"code_snippet\":\"sa_k3_dev = dev;\\n...\\nif (ret) {\\n    goto disable_pm;\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2342,\"why_this_location_matters\":\"This overwrites the global device pointer and sets global state that is never explicitly torn down in the error paths.\"},{\"code_snippet\":\"platform_set_drvdata(pdev, NULL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_remove\",\"line\":2415,\"why_this_location_matters\":\"Clears the driver data while active crypto TFMs might still be executing, directly setting up the NULL pointer dereference.\"},{\"code_snippet\":\"struct sa_crypto_data *pdata = dev_get_drvdata(sa_k3_dev);\\n...\\nif (req->size >= 256)\\n\\tdma_rx = pdata->dma_rx2;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":null,\"why_this_location_matters\":\"Active crypto requests post-unbind will fetch NULL pdata and crash here.\"},{\"code_snippet\":\"struct sa_crypto_data *data = dev_get_drvdata(sa_k3_dev);\\n...\\nsa_free_ctx_info(&ctx->enc, data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_exit\",\"line\":null,\"why_this_location_matters\":\"Releasing the active TFM calls sa_free_ctx_info with a NULL data pointer, crashing upon locking.\"}],\"patch_index\":9,\"patch_subject\":\"[PATCH 09/30] crypto: sa2ul - remove unused base register pointer\",\"preexisting\":true,\"reasoning\":\"1. In `sa_ul_probe`, the device pointer is saved to a global variable `sa_k3_dev = dev;`. If a second SA2UL accelerator is probed, this pointer is overwritten, corrupting the state for multi-instance systems.\\n2. On probe failure (e.g., `sa_init_mem` fails), `sa_k3_dev` is not reset to NULL, leaving a dangling pointer.\\n3. When the driver is unbound, `sa_ul_remove()` clears driver data via `platform_set_drvdata(pdev, NULL)` but active `crypto_tfm` instances can still be executing (e.g., via AF_ALG).\\n4. Any subsequent crypto operations (`sa_run`) or context releases (`sa_cipher_cra_exit`) will call `dev_get_drvdata(sa_k3_dev)`, get a NULL pointer, and crash when dereferencing it.\",\"type\":\"Architectural Flaw / Null Pointer Dereference\"}],\"concerns_count\":11,\"dismissed_concerns\":[{\"description\":\"Removing the `base` pointer from `struct sa_crypto_data` and its assignment in `sa_ul_probe` could break register accesses.\",\"locations\":[{\"code_snippet\":\"void __iomem *base;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_crypto_data\",\"line\":175,\"why_this_location_matters\":\"This field was correctly identified as unused and safely removed from the data structure.\"},{\"code_snippet\":\"- dev_data->base = saul_base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2345,\"why_this_location_matters\":\"This is where the baseline initialized the base pointer that was never actually read.\"},{\"code_snippet\":\"status = readl_relaxed(saul_base + SA_ENGINE_STATUS);\\n\\t/* Only enable engines if all are not already enabled */\\n\\tif (val & ~status)\\n\\t\\twritel_relaxed(val, saul_base + SA_ENGINE_ENABLE_CONTROL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2369,\"why_this_location_matters\":\"These are the only register accesses in the entire driver, and they properly operate directly on the local `saul_base` variable during probe.\"}],\"reasoning\":\"A comprehensive search of the codebase confirms that `dev_data->base` was entirely unused outside of its initial assignment in `sa_ul_probe`. All MMIO register accesses happen synchronously within `sa_ul_probe` using the local `saul_base` variable. Post-probe data path operations use DMA channels exclusively. Since it was a write-only field with no reads anywhere in the driver, removing it does not cause regressions, resource leakage, or missing I/O state.\",\"type\":\"Unused Code Removal\"}],\"dismissed_concerns_count\":1,\"findings\":[{\"locations\":[{\"code_snippet\":\"- \\tdev_data->base = saul_base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2345,\"why_this_location_matters\":\"This is the line removed based on the hallucinated justification.\"},{\"code_snippet\":\"static void __iomem *saul_base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2325,\"why_this_location_matters\":\"This is the actual base pointer used for register accesses, proving the commit message's claim about 'psilss_base' is incorrect.\"}],\"patch_index\":9,\"patch_subject\":\"[PATCH 09/30] crypto: sa2ul - remove unused base register pointer\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: commit message hallucinates nonexistent psilss_base pointer\",\"severity\":\"Medium\",\"severity_explanation\":\"Consequence: The commit message explicitly claims that the driver uses the 'psilss_base' pointer for register accesses, but this pointer does not exist anywhere in the driver or kernel tree. The actual pointer used is 'saul_base'. This introduces misleading documentation into the git history, complicating future maintenance and reviews.\\nTriggering path: Reading the commit history.\\nReachability: N/A. Capped at Medium severity per guidelines for 'Meaningful code and commit message mismatch'.\"}]}","patch_id":189874,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2817685,"tokens_in":3593854,"tokens_out":15726},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167763,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Off-by-one logic error in command label sizing enables an out-of-bounds write on the stack.\",\"locations\":[{\"code_snippet\":\"cmdl[sa_ctx->cmdl_size / sizeof(u32)] = req->type;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1098,\"why_this_location_matters\":\"This is the location where the out-of-bounds write occurs when `cmdl_size` hits the maximum allowed capacity.\"},{\"code_snippet\":\"if (cmdl_len <= 0 || (cmdl_len > SA_MAX_CMDL_WORDS * sizeof(u32)))\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_setkey\",\"line\":885,\"why_this_location_matters\":\"This capacity check allows `cmdl_size` to consume the entire array, leaving no room for the dynamically appended type flag.\"}],\"patch_index\":10,\"patch_subject\":\"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines\",\"preexisting\":true,\"reasoning\":\"1. In configuration routines (e.g., `sa_cipher_setkey`, `sa_aead_setkey`), `sa_format_cmdl_gen()` is used to construct a command label and returns its length (`cmdl_len`) in bytes.\\n2. The returned length is validated against `(cmdl_len > SA_MAX_CMDL_WORDS * sizeof(u32))`. If `cmdl_len` is exactly equal to `SA_MAX_CMDL_WORDS * sizeof(u32)`, the check incorrectly passes, and `ctx->cmdl_size` is set to this maximum value.\\n3. Later in `sa_run()`, the command label is copied into a local stack array `u32 cmdl[SA_MAX_CMDL_WORDS]`. This perfectly fills the array without overflowing.\\n4. However, immediately after, `sa_run()` appends a word to this label: `cmdl[sa_ctx->cmdl_size / sizeof(u32)] = req->type;`.\\n5. Because `cmdl_size / sizeof(u32)` equals `SA_MAX_CMDL_WORDS`, this statement writes exactly one 32-bit word past the end of the `cmdl` stack array, corrupting the stack.\\n6. The capacity checks throughout the driver should ensure `cmdl_len < SA_MAX_CMDL_WORDS * sizeof(u32)` to reserve space for the appended `req->type` word.\",\"type\":\"Stack Buffer Overflow\"},{\"description\":\"SHA initialization functions completely ignore error returns from internal setup algorithms, leading to crashes and incomplete contexts.\",\"locations\":[{\"code_snippet\":\"\\tsa_sha_cra_init_alg(tfm, \\\"sha1\\\");\\n...\\n\\tsa_sha_setup(ctx, &ad);\\n\\n\\treturn 0;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1557,\"why_this_location_matters\":\"This is where critical initialization errors are silently swallowed, guaranteeing a subsequent kernel panic when the fallback TFM is used.\"},{\"code_snippet\":\"\\t\\t\\treturn PTR_ERR(ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1459,\"why_this_location_matters\":\"This valid error path is completely disregarded by the caller.\"}],\"patch_index\":10,\"patch_subject\":\"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines\",\"preexisting\":true,\"reasoning\":\"1. In `sa_sha1_cra_init()` (and the sha256/sha512 variants), the code calls `sa_sha_cra_init_alg()` and `sa_sha_setup()`.\\n2. Both of these called functions can fail due to resource exhaustion (e.g., `crypto_alloc_ahash` returning `-ENOMEM` or an `ERR_PTR`) or invalid configurations, returning an error code (like `-EINVAL` or `PTR_ERR`).\\n3. However, `sa_sha1_cra_init()` unconditionally returns `0` (success) and ignores these error returns completely.\\n4. As a result, the crypto framework perceives the driver as successfully initialized for the hash, while internally, the driver's context contains uninitialized state or `ERR_PTR` objects.\\n5. When subsequent operations like `sa_sha_init()` or `sa_sha_update()` execute, they blindly dereference `ctx->fallback.ahash` (e.g., passing it into `ahash_request_set_tfm()`), resulting in a guaranteed kernel crash (NULL/ERR pointer dereference) under memory pressure.\",\"type\":\"Ignored Return Values / Unhandled Errors\"},{\"description\":\"Missing teardown and context cleanup in error paths of `cra_init` routines.\",\"locations\":[{\"code_snippet\":\"return PTR_ERR(child);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":837,\"why_this_location_matters\":\"The error path returns directly without cleaning up `ctx->enc` or `ctx->dec`.\"},{\"code_snippet\":\"return PTR_ERR(ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1457,\"why_this_location_matters\":\"This error path leaks the initialized `ctx->enc`.\"},{\"code_snippet\":\"return PTR_ERR(ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1464,\"why_this_location_matters\":\"This error path leaks both `ctx->enc` and `ctx->shash`.\"},{\"code_snippet\":\"return ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1682,\"why_this_location_matters\":\"This error path leaks `ctx->shash` and `ctx->fallback.aead`.\"},{\"code_snippet\":\"return ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1688,\"why_this_location_matters\":\"This error path frees `ctx->enc` but still leaks `ctx->shash` and `ctx->fallback.aead`.\"}],\"patch_index\":10,\"patch_subject\":\"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines\",\"preexisting\":true,\"reasoning\":\"1. In `sa_cipher_cra_init()`, the driver allocates hardware context structures mapping DMA memory (`ctx->enc`, `ctx->dec`). If the fallback allocation (`crypto_alloc_skcipher`) fails, the function returns immediately without calling `sa_free_ctx_info()`, permanently leaking the DMA memory and context bitmap slots.\\n2. In `sa_sha_cra_init_alg()`, if `crypto_alloc_ahash` fails, it aborts without releasing the `ctx->shash` resource allocated immediately before it, nor freeing the `ctx->enc` context.\\n3. Similarly, in `sa_cra_init_aead()`, failures in fallback aead allocation or subsequent `sa_init_ctx_info` allocations return immediately without freeing the previously allocated `ctx->shash` and `ctx->fallback.aead` instances.\",\"type\":\"Memory Leak\"},{\"description\":\"The assoclen field is silently truncated to 8 bits when assigned to enc_offset, leading to incorrect hardware crypto operations for large AAD.\",\"locations\":[{\"code_snippet\":\"sa_req.enc_offset = req->assoclen;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_run\",\"line\":1857,\"why_this_location_matters\":\"This is where the unsafe assignment and integer truncation occurs before passing the request to the hardware runner.\"}],\"patch_index\":10,\"patch_subject\":\"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines\",\"preexisting\":true,\"reasoning\":\"1. In `sa_aead_run()`, the hardware request's offset `sa_req.enc_offset` is assigned the value of `req->assoclen`.\\n2. `sa_req.enc_offset` is defined as a `u8`, while `req->assoclen` is a `u32` (or unsigned int).\\n3. If `assoclen` exceeds 255 (which is valid and fits within the global `SA_MAX_DATA_SZ` limit of 65535), the assignment silently truncates the value.\\n4. The hardware command label utilizes an 8-bit field for the SOP bypass length (enc_offset), meaning the hardware inherently does not support AAD sizes > 255 bytes.\\n5. Because the driver lacks a fallback check for `assoclen > 255`, this truncation causes the hardware accelerator to begin encryption/decryption at a wrapped-around, incorrect offset. This corrupts the AAD in the destination buffer and results in broken confidentiality and invalid MAC generation/verification.\",\"type\":\"Integer Truncation / Data Corruption\"},{\"description\":\"Unconditional byte swapping using swab32() breaks Big-Endian support.\",\"locations\":[{\"code_snippet\":\"for (i = 0; i < total / 4; i++)\\n\\t\\tword_ptr[i] = swab32(word_ptr[i]);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":643,\"why_this_location_matters\":\"Unconditional swab32 on the command label payload before sending it to the DMA engine.\"},{\"code_snippet\":\"for (i = 0; i < (authsize / 4); i++)\\n\\t\\tmdptr[i + 4] = swab32(mdptr[i + 4]);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_dma_in_callback\",\"line\":1699,\"why_this_location_matters\":\"Unconditional swab32 on the received authentication tag metadata.\"}],\"patch_index\":10,\"patch_subject\":\"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines\",\"preexisting\":true,\"reasoning\":\"1. In `sa_format_cmdl_gen()`, the command label is unconditionally byte-swapped using `swab32()`. \\n2. In `sa_aead_dma_in_callback()`, the incoming metadata (authentication tag) is unconditionally byte-swapped using `swab32()`.\\n3. While this works on Little-Endian systems (where `swab32()` is functionally equivalent to `cpu_to_be32()` or `be32_to_cpu()`), it will doubly-swap or incorrectly reverse the bytes on a Big-Endian system. Standard endianness macros like `cpu_to_be32()` or `be32_to_cpu()` should be used to ensure portability.\",\"type\":\"Endianness Bug\"}],\"concerns_count\":8,\"dismissed_concerns\":[{\"description\":\"Removing fields like `auth_iv` from `struct sa_req`, `keylen` from `struct sa_tfm_ctx`, and `cmdl` from the SHA request context could cause compilation failures or leave critical state uninitialized.\",\"locations\":[{\"code_snippet\":\"static inline void sa_update_cmdl(struct sa_req *req, u32 *cmdl, ...)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":615,\"why_this_location_matters\":\"Verifies that functions interacting with `struct sa_req` were already cleanly updated to no longer rely on `req->auth_iv`.\"},{\"code_snippet\":\"sa_copy_iv((void *)&cmdl[upd_info->auth_iv.index], req->auth_iv, (upd_info->auth_iv.size > 8));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":675,\"why_this_location_matters\":\"This is where `req->auth_iv` was previously utilized before being safely removed in a preceding cleanup commit.\"}],\"reasoning\":\"A comprehensive search reveals that none of these fields (e.g., `req->auth_iv`, `ctx->keylen`, `rctx->dev_data`) are referenced anywhere in `drivers/crypto/sa2ul.c` at the target commit. A prior version actively referenced `req->auth_iv` in `sa_update_cmdl()` when handling `SA_CMDL_UPD_AUTH_IV`, but an earlier patch identified that the `SA_CMDL_UPD_AUTH_IV` flag is never set and removed the dead code block entirely. Thus, these fields are remnants of prior refactoring, and their removal does not alter behavior, incorrectly change memory layouts, or cause build breaks.\",\"type\":\"Build Breakage / Unused Field Reference\"},{\"description\":\"Removing the large `cmdl` array from `struct sa_sha_req_ctx` drastically shrinks the struct's size, which might lead to buffer overflows if `.halg.statesize` scaling is incorrect.\",\"locations\":[{\"code_snippet\":\"crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),\\n\\t\\t\\t\\t sizeof(struct sa_sha_req_ctx) +\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1473,\"why_this_location_matters\":\"This is where the dynamic size calculation proves that shrinking the struct is perfectly safe and handled correctly.\"},{\"code_snippet\":\".halg.statesize = sizeof(struct sa_sha_req_ctx) + sizeof(struct sha1_state),\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init (struct ahash_alg definition)\",\"line\":2008,\"why_this_location_matters\":\"This demonstrates how the crypto subsystem allocates state memory based on `sizeof(struct sa_sha_req_ctx)`. Shrinking the struct size automatically adapts the statesize.\"}],\"reasoning\":\"`struct sa_sha_req_ctx` is purely a software-side request context used to track the fallback hashing request. The hardware does not DMA to it (it uses `sa_ctx_info->cmdl` instead). By removing the genuinely unused `cmdl` array, the overall `sizeof(struct sa_sha_req_ctx)` shrinks, which beneficially and safely propagates into the calculated `.halg.statesize`. The fallback hashing algorithm (e.g., software sha1) only requires the statesize of its own context plus the now-reduced `sa_sha_req_ctx` wrapper, meaning no under-allocation or overflow will occur during dynamic calls to `crypto_ahash_set_reqsize` or static framework allocations.\",\"type\":\"Memory Corruption / Struct Size Change\"},{\"description\":\"Removal of fields like `aalg`, `akey`, and `akey_len` from `struct sa_cmdl_cfg` could potentially break hardware communication if this struct is mapped or sent to the device.\",\"locations\":[{\"code_snippet\":\"struct sa_cmdl_cfg {\\n\\tu8 enc_eng_id;\\n\\tu8 auth_eng_id;\\n\\tu8 iv_size;\\n\\tbool enc;\\n};\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cmdl_cfg\",\"line\":96,\"why_this_location_matters\":\"Shows the struct definition after removal of the fields, confirming it holds basic parameters and is not a DMA descriptor.\"}],\"reasoning\":\"Investigation into how `struct sa_cmdl_cfg` is utilized shows that it is purely an internal software configuration struct allocated on the stack (e.g., in `sa_sha_setup` and `sa_aead_setkey`). It serves to group parameters for the `sa_format_cmdl_gen` function. It is never mapped for DMA or passed to hardware, so removing unused fields is entirely safe and does not alter any hardware layout.\",\"type\":\"Hardware Interface Change\"},{\"description\":\"The removal of the `sa_copy_iv` function could break the `SA_CMDL_UPD_ENC_IV` block, which also needs to copy IVs into the command label.\",\"locations\":[{\"code_snippet\":\"if (likely(upd_info->flags & SA_CMDL_UPD_ENC_IV)) {\\n\\t__be32 *data = (__be32 *)&cmdl[upd_info->enc_iv.index];\\n\\tu32 *enc_iv = (u32 *)req->enc_iv;\\n\\n\\tfor (j = 0; i < upd_info->enc_iv.size; i += 4, j++) {\\n\\t\\tdata[j] = cpu_to_be32(*enc_iv);\\n\\t\\tenc_iv++;\\n\\t}\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":645,\"why_this_location_matters\":\"Proves that ENC_IV has its own inline copy logic and does not rely on `sa_copy_iv`.\"}],\"reasoning\":\"The `SA_CMDL_UPD_ENC_IV` logic within `sa_update_cmdl()` handles its own endian-swapping copy via an explicit `for` loop using `cpu_to_be32()`. The `sa_copy_iv()` function was only used by the `SA_CMDL_UPD_AUTH_IV` flag handler. Because `SA_CMDL_UPD_AUTH_IV` was never set anywhere in the driver, that entire code block and its dependency `sa_copy_iv()` were functionally dead code, making their removal correct.\",\"type\":\"Missing Function Implementation\"},{\"description\":\"The removal of `sc_id_start` from `struct sa_crypto_data` and substituting its usage with 0 might alter context ID allocation logic.\",\"locations\":[{\"code_snippet\":\"bn = ctx->sc_id;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":754,\"why_this_location_matters\":\"Shows where `data->sc_id_start` was safely eliminated from the subtraction because it was always zero.\"}],\"reasoning\":\"Searching the baseline code reveals that `sc_id_start` was read in both `sa_init_ctx_info` and `sa_free_ctx_info` but was never actually assigned a value anywhere in the driver. Since `struct sa_crypto_data` is allocated with `devm_kzalloc`, `sc_id_start` was implicitly always 0. Removing it and replacing it with 0 in the calculations preserves the exact original semantics.\",\"type\":\"State Management\"},{\"description\":\"Potential leak of uninitialized kernel memory due to an oversized statesize allocation in AHASH operations.\",\"locations\":[{\"code_snippet\":\"return crypto_ahash_export(subreq, out);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_export\",\"line\":1543,\"why_this_location_matters\":\"This is where the fallback export function writes less data than the framework allocated, leading to uninitialized bytes in the internal state buffer.\"},{\"code_snippet\":\".halg.statesize\\t\\t= sizeof(struct sa_sha_req_ctx) +\\n\\t\\t\\t\\t\\t  sizeof(struct sha1_state),\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1995,\"why_this_location_matters\":\"This is where the incorrectly oversized state size is declared to the crypto framework.\"}],\"reasoning\":\"1. The driver initializes `.halg.statesize` to an overallocated size: `sizeof(struct sa_sha_req_ctx) + sizeof(struct sha1_state)`.\\n2. During socket duplication or state export, the AF_ALG framework allocates a buffer of this large size.\\n3. In `sa_sha_export()`, the driver directly delegates to the fallback algorithm's export function.\\n4. The fallback export only writes `sizeof(struct sha1_state)` bytes to the `out` buffer, leaving trailing bytes uninitialized.\\n5. However, this oversized state buffer is exclusively used internally by the kernel (e.g., in `hash_accept()` within `algif_hash`) to temporarily hold the state before re-importing it to the child socket. The raw buffer is never exposed or copied to userspace via `getsockopt` or `recvmsg`, completely mitigating the information leak risk.\",\"type\":\"Information Leak\"},{\"description\":\"Possible hardware overrun if sg_split fails and fallback maps the entire original scatterlist.\",\"locations\":[{\"code_snippet\":\"ret = sg_split(mapped_sg->sgt.sgl, mapped_sg->sgt.nents, 0, 1, &split_size, &dst, &dst_nents, gfp_flags);\\nif (ret) {\\n\\tdst_nents = mapped_sg->sgt.nents;\\n\\tdst = mapped_sg->sgt.sgl;\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1184,\"why_this_location_matters\":\"The fallback path explicitly reuses the original scatterlist if splitting fails, which could initially appear as an overrun risk.\"}],\"reasoning\":\"In `sa_run()`, if `sg_split()` fails to slice the scatterlist to the exact `req->size`, the driver falls back to mapping the entire original scatterlist (`mapped_sg->split_sg = dst`). Although the DMA engine will be configured to handle the full length of the original scatterlist entry (which could be larger than `req->size`), the SA2UL hardware command label is correctly programmed with the exact `req->size` via `SA_CMDL_PAYLOAD_LENGTH_MASK`. Thus, the hardware will only push/pull exactly the required payload length to/from the DMA channels, cleanly terminating the transfer without causing out-of-bounds corruption.\",\"type\":\"DMA Buffer Overrun\"}],\"dismissed_concerns_count\":7,\"findings\":[]}","patch_id":189875,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":8277481,"tokens_in":9756988,"tokens_out":35310},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167761,"inline_review":"commit 63285c00a6997e5596e25cb2d8f7e12404eaeb2d\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - fix struct documentation for match_data\n\nThis commit aims to fix the structure documentation in sa2ul.h. It updates\nthe documentation for struct sa_crypto_data to rename @soc_data to\n@match_data.\n\n> Update structure name in documentation comment from sa_of_data\n> to sa_match_data to match the actual structure definition.\n\n[Severity: Medium]\nThis isn't a bug in the code, but is this commit message description accurate?\n\nThe diff actually renames the member '@soc_data' to '@match_data' within\n'struct sa_crypto_data', rather than renaming a structure from 'sa_of_data'\nto 'sa_match_data'.\n\nCould the commit message be updated to precisely reflect the actual code\nchanges?\n\nWhile reviewing the documentation changes in this file, I noticed an issue\nwith another structure in drivers/crypto/sa2ul.h:\n\n>  /**\n>   * struct sa_tfm_ctx: TFM context structure\n>   * @dev_data: struct sa_crypto_data pointer\n>   * @enc: struct sa_ctx_info for encryption\n>   * @dec: struct sa_ctx_info for decryption\n>   * @iv_idx: Initialization vector index\n>   * @key: encryption key\n>   * @fallback: SW fallback algorithm\n>   */\n>  struct sa_tfm_ctx {\n>  \tstruct sa_crypto_data *dev_data;\n>  \tstruct sa_ctx_info enc;\n>  \tstruct sa_ctx_info dec;\n>  \tint iv_idx;\n>  \tstruct crypto_shash\t*shash;\n\n[Severity: Low]\nDoes the kernel-doc for struct sa_tfm_ctx need updating?\n\nThe documentation block includes a '@key' field which has been removed from\nthe structure, and it is missing the '@shash' field that is currently present.\nRunning scripts/kernel-doc or building documentation will yield warnings for\nthese out-of-sync fields.\n\nCould this documentation also be updated to match the structure definition?","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":4,\"dismissed_concerns\":[{\"description\":\"Candidate concern that the newly documented field `@match_data` might not correspond to an actual field in the structure definition.\",\"locations\":[{\"code_snippet\":\"\\tconst struct sa_match_data *match_data;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_crypto_data\",\"line\":177,\"why_this_location_matters\":\"This struct member definition proves that the updated kernel-doc correctly reflects the underlying C structure.\"}],\"reasoning\":\"A review of the `struct sa_crypto_data` definition further down in the header confirms that it contains the field `const struct sa_match_data *match_data;`. The patch correctly resolves a kernel-doc mismatch by updating the outdated `@soc_data` reference to `@match_data`.\",\"type\":\"Kernel-Doc Correctness\"}],\"dismissed_concerns_count\":1,\"findings\":[{\"locations\":[{\"code_snippet\":\"- * @soc_data: Pointer to SoC specific data\\n+ * @match_data: Pointer to match data\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_crypto_data\",\"line\":165,\"why_this_location_matters\":\"This is the actual documentation line modified by the patch, demonstrating the disconnect with the commit message.\"}],\"patch_index\":13,\"patch_subject\":\"[PATCH 13/30] crypto: sa2ul - fix struct documentation for match_data\",\"preexisting\":false,\"problem\":\"sa2ul: commit message meaningfully misrepresents struct rename\",\"severity\":\"Medium\",\"severity_explanation\":\"The consequence is confusion for maintainers and future readers reading the git history. The commit message explicitly claims to update the structure name from 'sa_of_data' to 'sa_match_data'. However, the diff actually renames the member '@soc_data' to '@match_data' within 'struct sa_crypto_data'. Since the commit message meaningfully misrepresents the code change and uses identifiers that do not exist, it is a mismatch (per severity.md: 'Meaningful code and commit message mismatch').\"},{\"locations\":[{\"code_snippet\":\" * @key: encryption key\\n * @fallback: SW fallback algorithm\\n */\\nstruct sa_tfm_ctx {\\n...\\n\\tint iv_idx;\\n\\tstruct crypto_shash\\t*shash;\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"struct sa_tfm_ctx\",\"line\":274,\"why_this_location_matters\":\"This documentation block contains out-of-sync fields introduced by earlier patches in the series, which this documentation-fixing patch failed to address.\"}],\"patch_index\":13,\"patch_subject\":\"[PATCH 13/30] crypto: sa2ul - fix struct documentation for match_data\",\"preexisting\":false,\"problem\":\"sa2ul: incomplete kerneldoc update for struct sa_tfm_ctx\",\"severity\":\"Low\",\"severity_explanation\":\"The consequence is that the kernel-doc for `struct sa_tfm_ctx` is out of sync with its definition, documenting a removed `@key` field and missing the `@shash` field. The triggering path is running `scripts/kernel-doc` or building documentation, which will yield warnings. Since there is no visible real-life effect on runtime functionality, it is a low severity issue (per severity.md: 'Missing documentation or comments').\"}]}","patch_id":189880,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":1366192,"tokens_in":1697691,"tokens_out":8160},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167755,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Missing bounds check after `find_first_zero_bit` leads to an out-of-bounds array write, corrupting the adjacent `dma_rx1` pointer.\",\"locations\":[{\"code_snippet\":\"bn = find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX);\\n__set_bit(bn, data->ctx_bm);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":774,\"why_this_location_matters\":\"This is where the out-of-bounds bit is blindly used to write to the bitmap array without validation, directly corrupting internal struct pointers.\"}],\"patch_index\":14,\"patch_subject\":\"[PATCH 14/30] crypto: sa2ul - zero out security context on free\",\"preexisting\":true,\"reasoning\":\"In `sa_init_ctx_info()`, `find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX)` is used to find a free context ID. If all 512 contexts are in use, `find_first_zero_bit` returns `SA_MAX_NUM_CTX` (512). The code blindly calls `__set_bit(bn, data->ctx_bm)` without checking if `bn < SA_MAX_NUM_CTX`. Since `data->ctx_bm` is an array sized for exactly 512 bits (8 `unsigned long`s on 64-bit systems), setting bit 512 writes into `ctx_bm[8]`. This is past the end of the `ctx_bm` array and overlaps exactly with the `dma_rx1` pointer in `struct sa_crypto_data`. This corrupts the DMA channel pointer, leading to a fatal system crash or potential memory corruption vulnerability.\",\"type\":\"Out-of-Bounds Write\"},{\"description\":\"Memory and resource leaks in multiple algorithm initialization error paths (`sa_cipher_cra_init`, `sa_sha_cra_init_alg`, `sa_cra_init_aead`).\",\"locations\":[{\"code_snippet\":\"if (IS_ERR(child)) {\\n\\tdev_err(sa_k3_dev, \\\"Error allocating fallback algo %s\\\\n\\\", name);\\n\\treturn PTR_ERR(child);\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":838,\"why_this_location_matters\":\"This error path fails to clean up earlier context allocations, leaking DMA memory and context IDs.\"},{\"code_snippet\":\"if (IS_ERR(ctx->shash)) {\\n\\tdev_err(sa_k3_dev, \\\"base driver %s couldn't be loaded\\\\n\\\",\\n\\t\\talg_base);\\n\\treturn PTR_ERR(ctx->shash);\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1454,\"why_this_location_matters\":\"The function aborts on error, leaking the previously allocated ctx->enc resources.\"},{\"code_snippet\":\"ret = sa_init_ctx_info(&ctx->enc, data);\\nif (ret)\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1676,\"why_this_location_matters\":\"If this initialization fails, the function returns without cleaning up ctx->shash and ctx->fallback.aead.\"}],\"patch_index\":14,\"patch_subject\":\"[PATCH 14/30] crypto: sa2ul - zero out security context on free\",\"preexisting\":true,\"reasoning\":\"The Linux crypto framework does not invoke the `cra_exit` callback when a `cra_init` function fails. Therefore, any resources allocated during `cra_init` must be explicitly cleaned up before returning an error.\\n1. In `sa_cipher_cra_init`, if `crypto_alloc_skcipher` fails, it returns without freeing `ctx->enc` and `ctx->dec`.\\n2. In `sa_sha_cra_init_alg`, if `crypto_alloc_shash` or `crypto_alloc_ahash` fails, it returns without freeing `ctx->enc` and `ctx->shash`.\\n3. In `sa_cra_init_aead`, if `crypto_alloc_aead` or `sa_init_ctx_info` fails, it returns without freeing `ctx->shash`, `ctx->fallback.aead`, and/or `ctx->enc`.\\nThese paths indefinitely leak the `dma_pool` memory, context bitmap tracking bits, and fallback transform allocations.\",\"type\":\"Memory Leak\"},{\"description\":\"Hash initialization functions ignore the return value of `sa_sha_cra_init_alg`, leading to unhandled failures and subsequent NULL pointer dereferences.\",\"locations\":[{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1546,\"why_this_location_matters\":\"The initialization function can fail, but its return value is completely ignored, passing broken state to subsequent calls.\"}],\"patch_index\":14,\"patch_subject\":\"[PATCH 14/30] crypto: sa2ul - zero out security context on free\",\"preexisting\":true,\"reasoning\":\"`sa_sha1_cra_init` (and its SHA256/SHA512 variants) calls `sa_sha_cra_init_alg(tfm, \\\"sha1\\\")` but completely ignores its return value. If `sa_sha_cra_init_alg` fails (e.g., due to failing to allocate DMA memory or base hashes), it returns an error pointer and leaves internal pointers (like `ctx->enc.sc`) uninitialized/NULL. The caller proceeds normally and unconditionally returns 0 (success) to the crypto framework. Subsequently, calls to `sa_sha_setup` will invoke `sa_init_sc`, which attempts to zero or dereference the unallocated `ctx->sc` pointer, causing an immediate kernel panic. Additionally, since the framework considers the initialization successful, `cra_exit` will eventually attempt to free the `ERR_PTR` stored in the context, leading to further crashes.\",\"type\":\"Unhandled Error / Null Pointer Dereference\"}],\"concerns_count\":23,\"dismissed_concerns\":[{\"description\":\"Possible out-of-bounds write or unmapped memory access when clearing memory via `memzero_explicit` in `sa_free_ctx_info`.\",\"locations\":[{\"code_snippet\":\"memzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":761,\"why_this_location_matters\":\"This is the newly added line performing the zeroization, which is safely constrained by the DMA pool allocation boundaries.\"}],\"reasoning\":\"The DMA pool `data->sc_pool` is explicitly initialized with the requested object size being exactly `SA_CTX_MAX_SZ` (`dma_pool_create(..., SA_CTX_MAX_SZ, ...)`). Since `dma_pool_alloc` guarantees a returned memory chunk of at least the configured pool object size, zeroing exactly `SA_CTX_MAX_SZ` bytes using the valid virtual address `ctx->sc` is perfectly safe and will not write outside the allocated block boundaries.\",\"type\":\"Out of Bounds Access\"},{\"description\":\"Calling `sa_free_ctx_info` could zero out DMA memory while it is still actively being processed by the crypto hardware.\",\"locations\":[{\"code_snippet\":\"memzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":761,\"why_this_location_matters\":\"The zeroing operates safely because it respects the lifecycle managed by the overarching crypto framework.\"}],\"reasoning\":\"The kernel crypto API design ensures that `cra_exit` callbacks (which invoke `sa_free_ctx_info`) are only triggered once a transform (TFM) has no ongoing operations and its reference count hits zero. Since no DMA operations for this specific context can be active during driver tear-down, wiping the context block is safe from race conditions.\",\"type\":\"Logic Error\"},{\"description\":\"Possible double free or NULL pointer dereference if `sa_free_ctx_info` is called on uninitialized contexts.\",\"locations\":[{\"code_snippet\":\"if (ctx->sc) {\\n\\tmemzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\\n\\tdma_pool_free(data->sc_pool, ctx->sc, ctx->sc_phys);\\n\\tctx->sc = NULL;\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":760,\"why_this_location_matters\":\"The if-guard safely handles unallocated contexts and pointer nullification prevents double frees.\"}],\"reasoning\":\"The `sa_free_ctx_info` function correctly wraps its memory cleanup block in `if (ctx->sc)`, safely bypassing unallocated contexts (which are initialized to zero). Furthermore, setting `ctx->sc = NULL` after freeing prevents any subsequent double-free vulnerabilities.\",\"type\":\"Resource Management\"},{\"description\":\"Potential sleep while holding a spinlock when calling `dma_pool_alloc` with `GFP_KERNEL` in `sa_init_ctx_info`.\",\"locations\":[{\"code_snippet\":\"spin_unlock(&data->scid_lock);\\n\\nctx->sc_id = (u16)bn;\\n\\nctx->sc = dma_pool_alloc(data->sc_pool, GFP_KERNEL, &ctx->sc_phys);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":776,\"why_this_location_matters\":\"This shows the spinlock is reliably released prior to the GFP_KERNEL allocation.\"}],\"reasoning\":\"The spinlock `&data->scid_lock` is explicitly unlocked immediately before calling `dma_pool_alloc` with `GFP_KERNEL`. Therefore, the memory allocation, which may sleep, is safely executed outside of the atomic spinlock context.\",\"type\":\"Sleeping in atomic context\"},{\"description\":\"Potential unsafe use of `spin_lock` without IRQ disable in `sa_free_ctx_info` and `sa_init_ctx_info`.\",\"locations\":[{\"code_snippet\":\"spin_lock(&data->scid_lock);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":755,\"why_this_location_matters\":\"This uses plain spin_lock, but is verified safe because all callers run in process context.\"}],\"reasoning\":\"The spinlock `data->scid_lock` is only acquired in `sa_init_ctx_info` and `sa_free_ctx_info`, both of which are exclusively called during TFM initialization (`cra_init`) and destruction (`cra_exit`). These callbacks always execute in process context, making plain `spin_lock` without `irqsave` safe and free from deadlock risks against interrupt handlers.\",\"type\":\"Lock Context Compatibility\"}],\"dismissed_concerns_count\":5,\"findings\":[]}","patch_id":189884,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2920183,"tokens_in":3742169,"tokens_out":26905},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466366,"id":167769,"inline_review":"commit 1cb836219f792e06c03cc55462dff92c974bbf83\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - remove redundant sa_sha_digest() wrapper\n\nThis commit removes the sa_sha_digest() wrapper function and updates the\nalgorithm definitions to directly use the function it was wrapping.\n\n>     Remove the sa_sha_digest() function which was a simple wrapper\n>     that only called crypto_shash_digest(). Replace all calls with\n>     direct crypto_shash_digest() calls.\n\n[Severity: Medium]\nIs this description accurate?\n\nThe code in drivers/crypto/sa2ul.c shows that sa_sha_digest() actually\nwrapped sa_sha_run(), and the subsequent updates to sa_algs replace the\ncalls with sa_sha_run() rather than crypto_shash_digest().\n\nCould the commit message be updated to accurately reflect the function being\nused?\n\n> diff --git a/drivers/crypto/sa2ul.c b/drivers/crypto/sa2ul.c\n> index c774447e7a5ab..673cd1458948f 100644\n> --- a/drivers/crypto/sa2ul.c\n> +++ b/drivers/crypto/sa2ul.c\n> @@ -1476,11 +1476,6 @@ static int sa_sha_cra_init_alg(struct crypto_tfm *tfm, const char *alg_base)\n>  \treturn 0;\n>  }\n>  \n> -static int sa_sha_digest(struct ahash_request *req)\n> -{\n> -\treturn sa_sha_run(req);\n> -}\n> -\n\n[ ... ]\n\n> @@ -1997,7 +1992,7 @@ static struct sa_alg_tmpl sa_algs[] = {\n>  \t\t\t.update\t\t\t= sa_sha_update,\n>  \t\t\t.final\t\t\t= sa_sha_final,\n>  \t\t\t.finup\t\t\t= sa_sha_finup,\n> -\t\t\t.digest\t\t\t= sa_sha_digest,\n> +\t\t\t.digest\t\t\t= sa_sha_run,","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":3,\"dismissed_concerns\":[{\"description\":\"Assigning `sa_sha_run` directly to the function pointers could cause a compilation error if it is not declared or defined before the assignments in `sa_algs[]`.\",\"locations\":[{\"code_snippet\":\"static int sa_sha_run(struct ahash_request *req)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_run\",\"line\":1363,\"why_this_location_matters\":\"Confirms the function is defined before its new usage as a function pointer.\"}],\"reasoning\":\"I checked the definition order. `sa_sha_run()` is fully defined around line 1363, which is well before the `sa_algs[]` array definition (starting around line 1895) where it is assigned to the `.digest` fields. Therefore, no forward declaration is missing.\",\"type\":\"Compilation Error (Forward Declaration)\"},{\"description\":\"Potential callback signature mismatch or execution flow alteration when replacing sa_sha_digest with sa_sha_run for the .digest callback, especially given the commit message's erroneous claim about crypto_shash_digest.\",\"locations\":[{\"code_snippet\":\"static int sa_sha_run(struct ahash_request *req)\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_run\",\"line\":1363,\"why_this_location_matters\":\"Shows that the signature of sa_sha_run perfectly matches the ahash callback requirement, proving no API contract violation.\"},{\"code_snippet\":\"- \\t\\t\\t.digest\\t\\t\\t= sa_sha_digest,\\n+ \\t\\t\\t.digest\\t\\t\\t= sa_sha_run,\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_algs\",\"line\":1995,\"why_this_location_matters\":\"This function pointer assignment proves that the substituted function perfectly matches the removed wrapper's behavior.\"}],\"reasoning\":\"The `.digest` callback in `struct ahash_alg` expects a function signature of `int (*digest)(struct ahash_request *req)`. The removed wrapper `sa_sha_digest` had this exact signature, simply returning `sa_sha_run(req)`. The newly assigned function `sa_sha_run` also has the exact signature `static int sa_sha_run(struct ahash_request *req)`. It perfectly matches the expected callback type and functionally operates exactly the same as the previous wrapper. The commit message's claim about `crypto_shash_digest` (which would expect a `struct shash_desc *` and thus cause a mismatch) is just a documentation error, and the actual code substitution introduces no behavioral or type safety regressions.\",\"type\":\"Type Mismatch / API Compatibility\"}],\"dismissed_concerns_count\":2,\"findings\":[{\"locations\":[{\"code_snippet\":\"-static int sa_sha_digest(struct ahash_request *req)\\n-{\\n-\\treturn sa_sha_run(req);\\n-}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_digest\",\"line\":1479,\"why_this_location_matters\":\"This shows the original wrapper actually called `sa_sha_run`, directly contradicting the claim in the commit message.\"},{\"code_snippet\":\"- \\t\\t\\t.digest\\t\\t\\t= sa_sha_digest,\\n+ \\t\\t\\t.digest\\t\\t\\t= sa_sha_run,\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_algs\",\"line\":1995,\"why_this_location_matters\":\"This diff hunk proves that sa_sha_run is used as the replacement, exposing the error in the commit message's claim about crypto_shash_digest().\"}],\"patch_index\":12,\"patch_subject\":\"[PATCH 12/30] crypto: sa2ul - remove redundant sa_sha_digest() wrapper\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: commit message hallucination regarding crypto_shash_digest()\",\"severity\":\"Medium\",\"severity_explanation\":\"Consequence: The git commit history is polluted with factually incorrect AI-generated claims about the code changes. Triggering path: N/A (documentation/commit message issue). Reachability: N/A. The severity is Medium per the severity guidelines for 'Meaningful code and commit message mismatch'.\"}]}","patch_id":189885,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":198436,"tokens_in":481132,"tokens_out":7622},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466367,"id":167768,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Missing bounds check on the return value of find_first_zero_bit() leads to an out-of-bounds write on the ctx_bm array.\",\"locations\":[{\"code_snippet\":\"\\tbn = find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX);\\n\\t__set_bit(bn, data->ctx_bm);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":780,\"why_this_location_matters\":\"This is where the unchecked return value of find_first_zero_bit is used in a bitwise operation, causing the out-of-bounds write.\"}],\"patch_index\":8,\"patch_subject\":\"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking\",\"preexisting\":true,\"reasoning\":\"In `sa_init_ctx_info()`, `find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX)` is used to find a free context ID. If all 512 contexts are in use, it returns `SA_MAX_NUM_CTX` (512). The code unconditionally proceeds to execute `__set_bit(bn, data->ctx_bm)`. Because `ctx_bm` is sized as `DIV_ROUND_UP(512, BITS_PER_LONG)`, it only contains enough capacity for exactly 512 bits (indices 0 to 511). Setting bit 512 writes past the end of the array, corrupting the subsequent fields in `struct sa_crypto_data` (specifically, it overwrites the lowest bit of the adjacent pointer `struct sa_tfm_ctx *ctx`). This pointer corruption will lead to a kernel panic upon dereference. An explicit check (e.g., `if (bn >= SA_MAX_NUM_CTX) return -ENOMEM;`) is required before setting the bit.\",\"type\":\"Out-of-Bounds Write / Memory Corruption\"},{\"description\":\"Multiple crypto algorithm initialization routines leak DMA pool memory, fallback crypto descriptors, and hardware tracking contexts on error paths.\",\"locations\":[{\"code_snippet\":\"\\tif (IS_ERR(child)) {\\n\\t\\tdev_err(sa_k3_dev, \\\"Error allocating fallback algo %s\\\\n\\\", name);\\n\\t\\treturn PTR_ERR(child);\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":849,\"why_this_location_matters\":\"The error path returns directly without calling `sa_free_ctx_info()` to clean up `ctx->enc` and `ctx->dec`.\"},{\"code_snippet\":\"if (IS_ERR(ctx->shash)) {\\n\\tdev_err(sa_k3_dev, \\\"base driver %s couldn't be loaded\\\\n\\\",\\n\\t\\talg_base);\\n\\treturn PTR_ERR(ctx->shash);\\n}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1500,\"why_this_location_matters\":\"The error path fails to free `ctx->enc` before returning.\"},{\"code_snippet\":\"ret = sa_init_ctx_info(&ctx->enc, data);\\nif (ret)\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1720,\"why_this_location_matters\":\"This error path returns without freeing both the previously allocated `ctx->shash` and `ctx->fallback.aead`.\"}],\"patch_index\":8,\"patch_subject\":\"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking\",\"preexisting\":true,\"reasoning\":\"In the kernel crypto API, if a `cra_init` callback fails and returns an error, the corresponding `cra_exit` handler is NOT automatically called. Thus, all resources allocated before the failure must be explicitly freed on the error path. \\n- In `sa_cipher_cra_init()`, if `crypto_alloc_skcipher()` fails, the previously allocated `ctx->enc` and `ctx->dec` hardware contexts and their DMA memory are not freed.\\n- In `sa_sha_cra_init_alg()`, if `crypto_alloc_shash()` or `crypto_alloc_ahash()` fails, the previously allocated `ctx->enc` (and potentially `ctx->shash`) are permanently leaked.\\n- In `sa_cra_init_aead()`, if context allocations or fallback initializations fail, previously allocated components like `ctx->shash` and `ctx->fallback.aead` are left behind.\\nOver time, these leaks will exhaust the 512 available hardware contexts and deplete DMA pools.\",\"type\":\"Memory Leak\"},{\"description\":\"The security context memory containing sensitive cryptographic keys is freed without being zeroized, violating subsystem key lifecycle guidelines.\",\"locations\":[{\"code_snippet\":\"\\tif (ctx->sc) {\\n\\t\\tdma_pool_free(data->sc_pool, ctx->sc, ctx->sc_phys);\\n\\t\\tctx->sc = NULL;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":776,\"why_this_location_matters\":\"This is where the DMA memory containing cryptographic key material is freed without prior zeroization.\"}],\"patch_index\":8,\"patch_subject\":\"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking\",\"preexisting\":true,\"reasoning\":\"Subsystem guidelines heavily restrict key lifecycle management, specifically dictating that keys must be zeroized after use. In `sa_set_sc_enc()`, cryptographic keys are copied into the hardware security context buffer (`sc_buf` / `ctx->sc`). Later, in `sa_free_ctx_info()`, this memory is returned to the DMA pool via `dma_pool_free()`. Because there is no call to `memzero_explicit()` (or similar wiping function) prior to freeing the context, sensitive key material lingers in the DMA pool memory. This poses a security risk, as the data could leak into other allocations or back to the system memory allocator when the pool is destroyed.\",\"type\":\"Key Material Leakage\"},{\"description\":\"The `sa_sha1_cra_init`, `sa_sha256_cra_init`, and `sa_sha512_cra_init` wrappers completely ignore the return values of `sa_sha_cra_init_alg` and `sa_sha_setup`, leading to incomplete TFM initialization.\",\"locations\":[{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\\n\\n\\tsa_sha_setup(ctx, &ad);\\n\\n\\treturn 0;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1571,\"why_this_location_matters\":\"The non-zero return values of initialization and setup functions are silently dropped, incorrectly guaranteeing success to the caller.\"}],\"patch_index\":8,\"patch_subject\":\"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking\",\"preexisting\":true,\"reasoning\":\"Functions like `sa_sha_cra_init_alg` and `sa_sha_setup` can fail due to resource exhaustion, memory allocation failures, or invalid fallback loading. However, the specific wrapper functions (e.g., `sa_sha1_cra_init`) call these routines but completely ignore their non-zero integer return values. They continue execution unconditionally and return `0` (success) to the crypto core subsystem. The subsystem will incorrectly consider the transform context as fully initialized and ready. When hashing operations are subsequently requested, the driver will dereference invalid pointers (like `IS_ERR` values) or uninitialized memory, leading to a kernel crash.\",\"type\":\"Unhandled Error Codes\"},{\"description\":\"Failure to reset `ctx->sc_id` on DMA allocation failure in `sa_init_ctx_info`.\",\"locations\":[{\"code_snippet\":\"scid_rollback:\\n\\tspin_lock(&data->scid_lock);\\n\\t__clear_bit(bn, data->ctx_bm);\\n\\tdata->sc_id--;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":800,\"why_this_location_matters\":\"The rollback path fails to clear `ctx->sc_id = 0` (or otherwise reset it to an invalid state) after having modified it.\"}],\"patch_index\":8,\"patch_subject\":\"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking\",\"preexisting\":true,\"reasoning\":\"In `sa_init_ctx_info`, `ctx->sc_id` is assigned the bitmap index (`bn`) before attempting the allocation via `dma_pool_alloc()`. If the allocation fails, the error handling path (`scid_rollback`) correctly clears the bit from `data->ctx_bm` and decrements `data->sc_id`, but it leaves `ctx->sc_id` holding the stale identifier value. While this is not immediately exploitable because callers generally discard the surrounding structure upon failure, it violates safe state teardown practices by leaving struct fields partially modified.\",\"type\":\"State Not Restored\"}],\"concerns_count\":20,\"dismissed_concerns\":[{\"description\":\"The removal of `sc_id_start` might cause the Security Context ID to be mapped or offset incorrectly, breaking hardware expectations.\",\"locations\":[{\"code_snippet\":\"bn = ctx->sc_id;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":767,\"why_this_location_matters\":\"This is where the offset subtraction was simplified.\"},{\"code_snippet\":\"ctx->sc_id = (u16)bn;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":788,\"why_this_location_matters\":\"This demonstrates the direct assignment after removing the statically zero offset component.\"}],\"reasoning\":\"A full tree analysis confirms that `sc_id_start` was only defined in the struct and used in these offset calculations, but it was never assigned a value. Because the parent structure is allocated via `devm_kzalloc()`, the `sc_id_start` field was intrinsically guaranteed to be exactly `0` at all times. Modifying the equations from `ctx->sc_id - data->sc_id_start` to just `ctx->sc_id` and from `data->sc_id_start + bn` to `bn` is mathematically identical and introduces no regressions.\",\"type\":\"Logic Error\"},{\"description\":\"Casting `bn` to `u16` could cause truncation if the index exceeds the maximum value of a 16-bit unsigned integer.\",\"locations\":[{\"code_snippet\":\"ctx->sc_id = (u16)bn;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":788,\"why_this_location_matters\":\"This is where the downcast to `u16` happens.\"}],\"reasoning\":\"The value of `bn` comes from `find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX)`. The macro `SA_MAX_NUM_CTX` is strictly hardcoded to 512, which comfortably fits within the 65,535 maximum bound of a `u16`. Even when the context bitmap is completely full (returning 512), no truncation occurs.\",\"type\":\"Integer Truncation\"}],\"dismissed_concerns_count\":2,\"findings\":[]}","patch_id":189872,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":3237522,"tokens_in":4172634,"tokens_out":24486},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466367,"id":167771,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Incomplete fix: Missing cleanup for ctx->shash and ctx->fallback.aead on subsequent error paths in sa_cra_init_aead().\",\"locations\":[{\"code_snippet\":\"\\tret = sa_init_ctx_info(&ctx->enc, data);\\n\\tif (ret)\\n\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1681,\"why_this_location_matters\":\"If encryption context initialization fails, the function returns without freeing ctx->shash or ctx->fallback.aead.\"},{\"code_snippet\":\"\\tret = sa_init_ctx_info(&ctx->dec, data);\\n\\tif (ret) {\\n\\t\\tsa_free_ctx_info(&ctx->enc, data);\\n\\t\\treturn ret;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1685,\"why_this_location_matters\":\"If decryption context initialization fails, it frees the encryption context but still returns without freeing ctx->shash or ctx->fallback.aead.\"}],\"patch_index\":17,\"patch_subject\":\"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. `sa_cra_init_aead()` successfully allocates resources for `ctx->shash` and `ctx->fallback.aead`.\\n2. It subsequently calls `sa_init_ctx_info()` to allocate DMA contexts for `ctx->enc` and `ctx->dec`.\\n3. If either `sa_init_ctx_info()` call fails, the function returns immediately.\\n4. Although this commit fixes a leak when `crypto_alloc_aead()` itself fails, it missed the subsequent error paths. `ctx->shash` and `ctx->fallback.aead` are permanently leaked when security context initialization fails, as the Crypto API does not call `.cra_exit` for transforms whose `.cra_init` function fails.\",\"type\":\"Memory Leak\"},{\"description\":\"Preexisting resource and memory leak in sa_sha_cra_init_alg() on error paths.\",\"locations\":[{\"code_snippet\":\"\\t\\tctx->shash = crypto_alloc_shash(alg_base, 0, 0);\\n\\t\\tif (IS_ERR(ctx->shash)) {\\n\\t\\t\\tdev_err(sa_k3_dev, \\\"base driver %s couldn't be loaded\\\\n\\\",\\n\\t\\t\\t\\talg_base);\\n\\t\\t\\treturn PTR_ERR(ctx->shash);\\n\\t\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1460,\"why_this_location_matters\":\"When shash allocation fails, the function returns directly without freeing the previously allocated ctx->enc context.\"},{\"code_snippet\":\"\\t\\t\\tcrypto_free_shash(ctx->shash);\\n\\t\\t\\treturn PTR_ERR(ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1470,\"why_this_location_matters\":\"When ahash allocation fails, the function correctly frees ctx->shash but returns without freeing the ctx->enc context.\"}],\"patch_index\":17,\"patch_subject\":\"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. `sa_sha_cra_init_alg()` successfully allocates a security context via `sa_init_ctx_info(&ctx->enc, data)`, which consumes a DMA pool allocation and a limited bitmap ID.\\n2. Later, the function attempts to allocate `ctx->shash` and `ctx->fallback.ahash`.\\n3. If either of these crypto allocation calls fail, the function immediately returns the error pointer.\\n4. It entirely fails to call `sa_free_ctx_info(&ctx->enc, data)` in these error paths, leading to a persistent leak of DMA memory and exhaustion of security context IDs.\",\"type\":\"Memory Leak\"},{\"description\":\"Ignored return value from initialization function hides errors, leading to NULL pointer dereferences later.\",\"locations\":[{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1557,\"why_this_location_matters\":\"The return value of the algorithm initialization function is ignored.\"},{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha256\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha256_cra_init\",\"line\":1572,\"why_this_location_matters\":\"The return value of the algorithm initialization function is ignored.\"},{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha512\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha512_cra_init\",\"line\":1587,\"why_this_location_matters\":\"The return value of the algorithm initialization function is ignored.\"}],\"patch_index\":17,\"patch_subject\":\"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. `sa_sha_cra_init_alg` allocates resources and returns an error code if initialization fails.\\n2. The wrappers for specific hash algorithms (`sa_sha1_cra_init`, `sa_sha256_cra_init`, `sa_sha512_cra_init`) call `sa_sha_cra_init_alg` but completely ignore its return value, unconditionally returning 0.\\n3. If initialization fails, the fallback hash context (`ctx->fallback.ahash`) will be left uninitialized (or as NULL since `memset` cleared the struct). When the algorithm is later utilized, functions like `sa_sha_init` will pass this uninitialized pointer to `ahash_request_set_tfm` and subsequently dereference it in `crypto_ahash_init`, leading to a crash.\",\"type\":\"Null Pointer Dereference\"},{\"description\":\"Unchecked return value from find_first_zero_bit leads to out-of-bounds bit setting.\",\"locations\":[{\"code_snippet\":\"__set_bit(bn, data->ctx_bm);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":775,\"why_this_location_matters\":\"Writes to the bitmap without validating that the index 'bn' is within bounds.\"}],\"patch_index\":17,\"patch_subject\":\"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. `data->ctx_bm` is an array sized to exactly `SA_MAX_NUM_CTX` (512) bits (`unsigned long ctx_bm[DIV_ROUND_UP(512, BITS_PER_LONG)]`).\\n2. When no bits are available, `find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX)` returns `SA_MAX_NUM_CTX` (512).\\n3. `sa_init_ctx_info` unconditionally takes this return value `bn` and executes `__set_bit(bn, data->ctx_bm)` without checking if `bn < SA_MAX_NUM_CTX`.\\n4. This causes `__set_bit` to write to bit index 512, which is outside the bounds of the `ctx_bm` array, corrupting adjacent structure members (such as `dma_rx1`).\",\"type\":\"Out-of-Bounds Memory Access\"},{\"description\":\"Stack buffer overflow in prepare_kipad and prepare_kopad due to unvalidated authentication key length.\",\"locations\":[{\"code_snippet\":\"for (i = 0; i < key_sz; i++)\\n\\t\\tk_ipad[i] = key[i] ^ 0x36;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"prepare_kipad\",\"line\":null,\"why_this_location_matters\":\"This is where the out-of-bounds write corrupts stack memory because key_sz is trusted implicitly.\"},{\"code_snippet\":\"for (i = 0; i < key_sz; i++)\\n\\t\\tk_opad[i] = key[i] ^ 0x5c;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"prepare_kopad\",\"line\":null,\"why_this_location_matters\":\"This location holds the identical overflow vulnerability while generating the outer padding.\"}],\"patch_index\":17,\"patch_subject\":\"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. `sa_aead_setkey()` processes a user-supplied key via `crypto_authenc_extractkeys()`. This utility extracts the length of the authentication key without imposing bounds checks based on block sizes.\\n2. This unvalidated length is eventually passed to `sa_prepare_iopads()` as `key_sz`.\\n3. `sa_prepare_iopads()` declares a 64-byte stack buffer (`sha.k_pad`).\\n4. `prepare_kipad()` loops precisely to the user-supplied length: `for (i = 0; i < key_sz; i++) k_ipad[i] = key[i] ^ 0x36;`.\\n5. If the user supplies an authentication key larger than 64 bytes, this loop will write out of bounds, corrupting the stack.\\n6. Standard HMAC dictates that keys longer than the block size must be hashed first; this step is missing in the current driver implementation.\",\"type\":\"Buffer Overflow\"}],\"concerns_count\":13,\"dismissed_concerns\":[{\"description\":\"Possible resource leak in sa_cipher_cra_init() error paths.\",\"locations\":[{\"code_snippet\":\"alloc_err:\\n\\tsa_free_ctx_info(&ctx->dec, data);\\nctx_dec_err:\\n\\tsa_free_ctx_info(&ctx->enc, data);\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":847,\"why_this_location_matters\":\"This demonstrates proper resource cleanup during initialization failure, proving this specific function does not suffer from the same leak found elsewhere in the driver.\"}],\"reasoning\":\"Since both sa_cra_init_aead() and sa_sha_cra_init_alg() exhibit missing unwinds on their error paths, it was plausible that sa_cipher_cra_init() had the same flaw. However, code inspection confirms that sa_cipher_cra_init() properly utilizes a goto-based cleanup strategy (alloc_err and ctx_dec_err labels), correctly calling sa_free_ctx_info() on allocated security contexts when subsequent fallback allocation steps fail.\",\"type\":\"Resource Management\"},{\"description\":\"Possible double-free or automatic cleanup by the Crypto API's exit function if `init` fails.\",\"locations\":[{\"code_snippet\":\"\\terr = frontend->init_tfm(tfm);\\n\\tif (err)\\n\\t\\tgoto out_free_tfm;\",\"file\":\"crypto/api.c\",\"function_or_symbol\":\"crypto_create_tfm_node\",\"line\":444,\"why_this_location_matters\":\"Demonstrates that if the initialization fails, the control flow bypasses the `cra_init_failed` block (which handles exit ops), proving that explicit driver-level cleanup is required.\"}],\"reasoning\":\"One might assume that the crypto subsystem's `crypto_destroy_tfm()` automatically calls the `.exit()` callback (which would invoke `sa_exit_tfm_aead` and free the resources) even if the `.init()` callback fails, thus making explicit cleanup in `sa_cra_init_aead` redundant or risking a double-free. However, exploring the Linux Crypto API in `crypto/api.c` reveals that if `alg->cra_init` (or `frontend->init_tfm`) fails, the framework immediately jumps to the error path (`out_free_tfm`) bypassing `crypto_exit_ops()`. Therefore, any resource allocated during `.init()` must be manually cleaned up on error by the driver, meaning the patch's addition of `crypto_free_shash()` is fundamentally correct and strictly necessary.\",\"type\":\"Resource Management\"},{\"description\":\"Possible missing cleanup of ctx->fallback.aead when its own allocation fails.\",\"locations\":[{\"code_snippet\":\"return PTR_ERR(ctx->fallback.aead);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1675,\"why_this_location_matters\":\"This is the return path where the allocation failure is handled.\"}],\"reasoning\":\"When crypto_alloc_aead fails, it returns an ERR_PTR, meaning the allocation was unsuccessful. The patch correctly cleans up the previously allocated ctx->shash before returning the error. There is no need to free ctx->fallback.aead because no object was actually allocated, so no memory leak occurs on this specific failure path.\",\"type\":\"Resource Management\"},{\"description\":\"Potential integer overflow in sa_aead_run when calculating auth_size = req->assoclen + req->cryptlen.\",\"locations\":[{\"code_snippet\":\"auth_size = req->assoclen + req->cryptlen;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_run\",\"line\":null,\"why_this_location_matters\":\"This is where the arithmetic addition takes place that theoretically flags as a wrapping vulnerability.\"}],\"reasoning\":\"While req->assoclen and req->cryptlen are 32-bit unsigned integers whose sum could theoretically overflow and wrap around to a small integer (bypassing the SA_MAX_DATA_SZ check), in practice they are strictly bounded by socket-level memory limits (e.g., AF_ALG memory limitations or scatterlist node maximums). These limits prevent users from supplying individual memory segments large enough (>= 4GB) to trigger a 32-bit integer wrap-around.\",\"type\":\"Integer Overflow\"}],\"dismissed_concerns_count\":4,\"findings\":[]}","patch_id":189878,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":1086946,"tokens_in":1524248,"tokens_out":18013},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466367,"id":167767,"inline_review":"commit 79bab3f1b9f753a0eb72a56fa469a57d9300345c\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - fix resource leak of sha in init_alg() error path\n\nThis commit attempts to fix a resource leak in the sha init error path\nby calling crypto_free_shash() when the fallback driver fails to load.\n\n> diff --git a/drivers/crypto/sa2ul.c b/drivers/crypto/sa2ul.c\n> index cd80a2dabc991..9379d12716983 100644\n> --- a/drivers/crypto/sa2ul.c\n> +++ b/drivers/crypto/sa2ul.c\n> @@ -1465,6 +1465,7 @@ static int sa_sha_cra_init_alg(struct crypto_tfm *tfm, const char *alg_base)\n>  \t\tif (IS_ERR(ctx->fallback.ahash)) {\n>  \t\t\tdev_err(ctx->dev_data->dev,\n>  \t\t\t\t\"Could not load fallback driver\\n\");\n> +\t\t\tcrypto_free_shash(ctx->shash);\n\n[Severity: High]\nDoes this create a dangling pointer that leads to a double free?\n\nWhile this frees ctx->shash, it does not set the pointer to NULL. It appears \nthat wrapper functions calling sa_sha_cra_init_alg(), such as \nsa_sha1_cra_init(), ignore the error return value and return 0 (success) \nto the crypto framework.\n\nBecause the framework believes the initialization succeeded, it will later\ninvoke the exit callback during teardown. The sa_sha_cra_exit() callback then\nunconditionally frees the dangling pointer, which can cause a kernel panic or\nmemory corruption:\n\nsa_sha1_cra_init()\n  sa_sha_cra_init_alg()\n    crypto_free_shash(ctx->shash); /* first free */\n    return error; /* wrapper ignores error */\n\n... later during teardown ...\n\nsa_sha_cra_exit()\n  crypto_free_shash(ctx->shash); /* double free */\n\nCould ctx->shash be set to NULL after being freed, or should the wrappers\nbe updated to properly propagate the error to the crypto framework?\n\n>  \t\t\treturn PTR_ERR(ctx->fallback.ahash);\n>  \t\t}\n>  \t}","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The return value of `sa_sha_cra_init_alg()` is entirely ignored by its callers, masking critical initialization failures and causing NULL pointer dereferences, Out-Of-Bounds writes, and state corruption.\",\"locations\":[{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1557,\"why_this_location_matters\":\"This is where the critical initialization error is silently swallowed.\"},{\"code_snippet\":\"memzero_explicit(sc_buf, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":718,\"why_this_location_matters\":\"If context allocation failed, `sc_buf` is NULL, triggering a kernel panic here.\"},{\"code_snippet\":\"ahash_request_set_tfm(&rctx->fallback_req, ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_init\",\"line\":1493,\"why_this_location_matters\":\"Because the request size wasn't set on the error path, writing to `rctx` causes a heap out-of-bounds write.\"},{\"code_snippet\":\"goto scid_rollback;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":782,\"why_this_location_matters\":\"Rolls back the ID state but does not zero ctx->sc_id.\"},{\"code_snippet\":\"__clear_bit(bn, data->ctx_bm);\\n\\tdata->sc_id--;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":749,\"why_this_location_matters\":\"During cleanup, performs a double decrement and double bit-clear because the crypto API mistakenly executed the exit routine for a failed init.\"}],\"patch_index\":16,\"patch_subject\":\"[PATCH 16/30] crypto: sa2ul - fix resource leak of sha in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. Functions like `sa_sha1_cra_init()` execute `sa_sha_cra_init_alg()` without checking or propagating its return value, unconditionally returning 0 to the framework.\\n2. If `sa_init_ctx_info()` fails, `ctx->enc.sc` remains NULL. `sa_sha_setup()` then calls `sa_init_sc()`, which performs `memzero_explicit(ctx->enc.sc, ...)`, causing a NULL pointer dereference panic.\\n3. If `crypto_alloc_ahash()` fails, `sa_sha_cra_init_alg()` returns early and bypasses `crypto_ahash_set_reqsize()`. The request context size remains 0, so when a hash operation is requested, `sa_sha_init()` writes to `rctx->fallback_req`, overflowing the heap buffer.\\n4. If context allocation failed, the internal state was rolled back but `ctx->sc_id` was left populated. Because the error is ignored, TFM destruction eventually calls `sa_free_ctx_info()`, double-decrementing `data->sc_id` and corrupting the DMA allocation bitmap.\",\"type\":\"Unhandled Error / Ignored Return Value\"},{\"description\":\"The driver's initialization routines lack comprehensive cleanup on error paths, leading to permanent leaks of DMA memory and cryptographic transform contexts.\",\"locations\":[{\"code_snippet\":\"return PTR_ERR(ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1469,\"why_this_location_matters\":\"Missing call to sa_free_ctx_info() prior to returning on this error path.\"},{\"code_snippet\":\"return PTR_ERR(ctx->fallback.aead);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1675,\"why_this_location_matters\":\"Missing crypto_free_shash() prior to returning on this error path.\"},{\"code_snippet\":\"return ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cra_init_aead\",\"line\":1682,\"why_this_location_matters\":\"Returns without freeing ctx->shash or ctx->fallback.aead after sa_init_ctx_info fails.\"}],\"patch_index\":16,\"patch_subject\":\"[PATCH 16/30] crypto: sa2ul - fix resource leak of sha in init_alg() error path\",\"preexisting\":true,\"reasoning\":\"1. In `sa_sha_cra_init_alg()`, if `crypto_alloc_ahash()` or `crypto_alloc_shash()` fail, the function returns without calling `sa_free_ctx_info(&ctx->enc, data)`. If the error propagation bug is fixed, this will leak the DMA descriptor pool and context ID.\\n2. In `sa_cra_init_aead()`, if `crypto_alloc_aead()` fails, it returns directly without freeing `ctx->shash`. If subsequent `sa_init_ctx_info()` calls fail, both `ctx->shash` and `ctx->fallback.aead` are left unfreed.\\n3. Since `sa_cra_init_aead()` correctly propagates error codes to the crypto core (unlike the SHA implementations), the `.cra_exit` callback is never called on failure, making these memory and context leaks unrecoverable.\",\"type\":\"Resource Leak\"}],\"concerns_count\":13,\"dismissed_concerns\":[{\"description\":\"Possible crash when `crypto_free_ahash` is called with an error pointer or a NULL pointer inside `sa_sha_cra_exit`.\",\"locations\":[{\"code_snippet\":\"crypto_free_ahash(ctx->fallback.ahash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_exit\",\"line\":1610,\"why_this_location_matters\":\"This is where the potentially NULL or error pointer is passed for freeing.\"},{\"code_snippet\":\"if (IS_ERR_OR_NULL(mem))\\n\\t\\treturn;\",\"file\":\"crypto/api.c\",\"function_or_symbol\":\"crypto_destroy_tfm\",\"line\":619,\"why_this_location_matters\":\"This confirms that the crypto API safely handles invalid tfm pointers during destruction.\"}],\"reasoning\":\"1. If `crypto_alloc_ahash` fails or is skipped, `ctx->fallback.ahash` contains an error pointer or NULL.\\n2. `sa_sha_cra_exit` calls `crypto_free_ahash(ctx->fallback.ahash)`.\\n3. `crypto_free_ahash` inline function passes the original pointer as the `mem` argument to `crypto_destroy_tfm`.\\n4. `crypto_destroy_tfm` immediately checks `if (IS_ERR_OR_NULL(mem))` and safely returns early without dereferencing anything. Therefore, this path handles both NULL and ERR_PTR correctly and is entirely safe.\",\"type\":\"Invalid Pointer Dereference\"}],\"dismissed_concerns_count\":1,\"findings\":[{\"locations\":[{\"code_snippet\":\"crypto_free_shash(ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_init_alg\",\"line\":1468,\"why_this_location_matters\":\"The patch adds this call, which frees the object but leaves a dangling pointer in ctx->shash.\"},{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1557,\"why_this_location_matters\":\"The wrapper ignores the error returned from sa_sha_cra_init_alg(), masking the failure from the crypto framework.\"},{\"code_snippet\":\"crypto_free_shash(ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_cra_exit\",\"line\":1609,\"why_this_location_matters\":\"The exit callback is invoked by the framework on teardown and unconditionally frees the dangling pointer, causing the double free panic.\"}],\"patch_index\":16,\"patch_subject\":\"[PATCH 16/30] crypto: sa2ul - fix resource leak of sha in init_alg() error path\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: double free of shash on init error path\",\"severity\":\"High\",\"severity_explanation\":\"Consequence: Double free of a `struct crypto_shash` kernel object, leading to memory corruption, kernel panic, or potential local privilege escalation.\\nTriggering path: An unprivileged user creates an AF_ALG socket for `sha1-sa2ul`, `sha256-sa2ul`, or `sha512-sa2ul`. If the underlying fallback algorithm allocation (`crypto_alloc_ahash`) fails (e.g., due to memory exhaustion), the error path is triggered.\\nReachability: Reachable from userspace via AF_ALG if the allocation can be made to fail.\\n\\nReasoning: \\n1. In `sa_sha_cra_init_alg()`, if `crypto_alloc_ahash()` fails, the patch calls `crypto_free_shash(ctx->shash)` to avoid a perceived leak, but does not set `ctx->shash` to `NULL`. This leaves a dangling pointer.\\n2. `sa_sha_cra_init_alg()` returns an error, but its callers (like `sa_sha1_cra_init()`) completely ignore this return value and unconditionally return 0 (success).\\n3. Because the wrapper returns 0, the crypto framework considers the TFM successfully initialized.\\n4. When the TFM is subsequently destroyed, the framework automatically invokes the `.cra_exit` callback, `sa_sha_cra_exit()`.\\n5. `sa_sha_cra_exit()` unconditionally calls `crypto_free_shash(ctx->shash)`, freeing the same pointer a second time.\"}]}","patch_id":189879,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2824956,"tokens_in":3499121,"tokens_out":20022},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466652,"id":167774,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Prepared DMA descriptor `tx_in` is leaked if the subsequent `tx_out` preparation fails.\",\"locations\":[{\"code_snippet\":\"\\t\\tdev_err(pdata->dev, \\\"OUT prep_slave_sg() failed\\\\n\\\");\\n\\t\\tret = -EINVAL;\\n\\t\\tgoto err_cleanup;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1234,\"why_this_location_matters\":\"This error path is taken after `tx_in` is already successfully allocated and prepared, bypassing any cleanup for it.\"},{\"code_snippet\":\"static void sa_free_sa_rx_data(struct sa_rx_data *rxd)\\n{\\n\\tint i;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_sa_rx_data\",\"line\":988,\"why_this_location_matters\":\"The cleanup function unmaps DMA regions and frees `split_sg`, but fails to handle the `tx_in` DMA descriptor.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. `sa_run()` successfully prepares a DMA descriptor `rxd->tx_in` using `dmaengine_prep_slave_sg()`.\\n2. Immediately afterward, it attempts to prepare `tx_out` with another `dmaengine_prep_slave_sg()` call.\\n3. If preparing `tx_out` fails, the code jumps to the `err_cleanup` label.\\n4. The `err_cleanup` path calls `sa_free_sa_rx_data(rxd)`, which cleans up scatterlist mappings and frees the `rxd` structure itself, but it does nothing to free or terminate the un-submitted `tx_in` descriptor.\\n5. According to the dmaengine API semantics, a prepared descriptor that is not submitted must be explicitly freed (e.g., via `dmaengine_desc_free()` if supported) or cleaned up by terminating the channel. Otherwise, it will remain leaked in the DMA provider's pool.\",\"type\":\"Resource Leak\"},{\"description\":\"Missing check on the return value of dmaengine_desc_get_metadata_ptr().\",\"locations\":[{\"code_snippet\":\"mdptr = (u32 *)dmaengine_desc_get_metadata_ptr(tx_out, &pl, &ml);\\n\\nsa_prepare_tx_desc(mdptr, ...);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":null,\"why_this_location_matters\":\"This is where the API is called and the unvalidated pointer is passed to a function that writes to it.\"},{\"code_snippet\":\"mdptr = (__be32 *)dmaengine_desc_get_metadata_ptr(rxd->tx_in, &pl, &ml);\\n...\\nresult[i] = be32_to_cpu(mdptr[i + rxd->iv_idx]);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_dma_in_callback\",\"line\":null,\"why_this_location_matters\":\"The callback reads from the potentially invalid metadata pointer without validation.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. `dmaengine_desc_get_metadata_ptr()` can return an error pointer (e.g., `ERR_PTR(-ENOTSUPP)`) if the DMA channel does not support metadata operations.\\n2. The driver unconditionally assigns the result to `mdptr` in multiple places (e.g., in `sa_run`, `sa_aes_dma_in_callback`, and `sa_aead_dma_in_callback`) without using `IS_ERR()` or checking for NULL.\\n3. Functions like `sa_prepare_tx_desc(mdptr, ...)` immediately dereference `mdptr`, which will cause a kernel panic if the DMA driver returns an error pointer.\\n4. While the specific underlying hardware (TI K3) may support metadata, relying on undocumented guarantees and failing to check API contracts violates safe kernel programming practices.\",\"type\":\"NULL/ERR_PTR Dereference\"},{\"description\":\"The return values of dmaengine_submit() are ignored, which can lead to a silent hang and resource leaks.\",\"locations\":[{\"code_snippet\":\"dmaengine_submit(tx_out);\\ndmaengine_submit(rxd->tx_in);\\n\\ndma_async_issue_pending(dma_rx);\\ndma_async_issue_pending(pdata->dma_tx);\\n\\nreturn -EINPROGRESS;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":null,\"why_this_location_matters\":\"The lack of dma_submit_error() checks here allows silent failure and resource leaks.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. `dmaengine_submit()` returns a `dma_cookie_t` which must be validated using `dma_submit_error()` to ensure the transfer was successfully enqueued.\\n2. If submission fails (e.g., due to exhausted internal DMA descriptors or channel errors), the callback will never be executed.\\n3. Because `sa_run()` ignores the submission status and unconditionally returns `-EINPROGRESS`, a failed submission will cause the crypto request to hang indefinitely waiting for completion.\\n4. Additionally, `rxd` and all associated DMA mappings will be permanently leaked since `sa_free_sa_rx_data()` is only invoked by the callback or explicit error paths.\",\"type\":\"Missing Error Handling\"},{\"description\":\"The DMA metadata buffer size is not checked against the maximum length provided by the DMA engine.\",\"locations\":[{\"code_snippet\":\"mdptr = (u32 *)dmaengine_desc_get_metadata_ptr(tx_out, &pl, &ml);\\n\\nsa_prepare_tx_desc(mdptr, ...);\\n\\nml = sa_ctx->cmdl_size + (SA_PSDATA_CTX_WORDS * sizeof(u32));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":null,\"why_this_location_matters\":\"The max length `ml` returned by the API is ignored and overwritten without validating that the upcoming writes will fit.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. `dmaengine_desc_get_metadata_ptr()` populates the `ml` variable with the maximum allowed metadata size for the descriptor.\\n2. `sa_run()` completely ignores this upper bound, immediately overwriting `ml` with its own computed size.\\n3. `sa_prepare_tx_desc()` then writes `epiblen` + `pslen` bytes into the `mdptr` buffer without any bounds validation against the original max length.\\n4. If the crypto command label (`sa_ctx->cmdl_size`) and PSDATA exceed the DMA channel's maximum metadata size, this will silently overflow the DMA driver's metadata buffer, leading to memory corruption.\",\"type\":\"Buffer Overflow\"},{\"description\":\"Ignoring sg_split() errors leads to excessive data being sent to the crypto engine, causing hardware FIFO desynchronization.\",\"locations\":[{\"code_snippet\":\"\\t\\tret = sg_split(mapped_sg->sgt.sgl, mapped_sg->sgt.nents, 0, 1,\\n\\t\\t\\t       &split_size, &src, &src_nents, gfp_flags);\\n\\t\\tif (ret) {\\n\\t\\t\\tsrc_nents = mapped_sg->sgt.nents;\\n\\t\\t\\tsrc = mapped_sg->sgt.sgl;\\n\\t\\t} else {\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1162,\"why_this_location_matters\":\"This is where the sg_split() error is ignored, falling back to sending the excessively large scatterlist via TX DMA.\"},{\"code_snippet\":\"\\t\\t\\tret = sg_split(mapped_sg->sgt.sgl, mapped_sg->sgt.nents,\\n\\t\\t\\t\\t       0, 1, &split_size, &dst, &dst_nents,\\n\\t\\t\\t\\t       gfp_flags);\\n\\t\\t\\tif (ret) {\\n\\t\\t\\t\\tdst_nents = mapped_sg->sgt.nents;\\n\\t\\t\\t\\tdst = mapped_sg->sgt.sgl;\\n\\t\\t\\t} else {\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1205,\"why_this_location_matters\":\"This is where the sg_split() error is similarly ignored for the RX DMA scatterlist.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. The driver correctly determines that the input scatterlist length might exceed the requested payload size (req->size) and calls sg_split() to truncate it.\\n2. If sg_split() fails (e.g. due to -ENOMEM), the code explicitly ignores the error and restores the scatterlist variables to point to the original, full-length scatterlist.\\n3. dmaengine_prep_slave_sg() is then called with the full scatterlist, which programs the TX DMA to transfer all bytes.\\n4. The SA2UL hardware receives the metadata specifying a payload of req->size but receives more bytes than that from the DMA. The excess bytes remain in the hardware FIFO and will be interpreted as the security context (command label) for the next packet.\\n5. Since an attacker can control the trailing bytes of the scatterlist (e.g., via AF_ALG sockets), they can inject arbitrary commands to the crypto hardware, leading to potential key extraction, memory corruption, or DoS.\",\"type\":\"Hardware Command Injection\"},{\"description\":\"Out-of-bounds write in sa_init_ctx_info due to missing bounds check on allocated context ID\",\"locations\":[{\"code_snippet\":\"__set_bit(bn, data->ctx_bm);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":775,\"why_this_location_matters\":\"This is where the out-of-bounds bit setting corrupts the adjacent struct member.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. sa_init_ctx_info() calls find_first_zero_bit(data->ctx_bm, SA_MAX_NUM_CTX).\\n2. If all 512 contexts are in use, find_first_zero_bit() returns SA_MAX_NUM_CTX (512).\\n3. The code then unconditionally executes __set_bit(bn, data->ctx_bm).\\n4. Because ctx_bm is declared as unsigned long ctx_bm[DIV_ROUND_UP(512, BITS_PER_LONG)], it contains exactly 8 longs (on 64-bit systems).\\n5. Setting bit 512 accesses index 8, which is out of bounds, and overwrites the immediately following field in struct sa_crypto_data (struct dma_chan *dma_rx1), corrupting the DMA channel pointer and causing a kernel panic upon subsequent DMA operations.\",\"type\":\"Memory Corruption\"},{\"description\":\"Out-of-bounds array read in sa_aead_setkey due to flawed signed integer bounds check\",\"locations\":[{\"code_snippet\":\"ad->mci_enc = mci_cbc_enc_no_iv_array[key_idx];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_setkey\",\"line\":null,\"why_this_location_matters\":\"This is where the negative array index triggers an out-of-bounds read.\"}],\"patch_index\":18,\"patch_subject\":\"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths\",\"preexisting\":true,\"reasoning\":\"1. In sa_aead_setkey(), crypto_authenc_extractkeys() is used to extract the user-provided keys. The user controls the length of keys.enckeylen.\\n2. The code calculates int key_idx = (keys.enckeylen >> 3) - 2;\\n3. The bounds check is if (key_idx >= 3) return -EINVAL;\\n4. If keys.enckeylen is less than 16 (e.g., 8), key_idx becomes negative (-1).\\n5. The signed integer comparison (-1 >= 3) evaluates to false, completely bypassing the check.\\n6. The code then accesses mci_cbc_enc_no_iv_array[key_idx], reading out of bounds and leaking kernel memory into the hardware security context.\",\"type\":\"Out-of-bounds Read\"}],\"concerns_count\":9,\"dismissed_concerns\":[{\"description\":\"The commit claims to fix a DMA resource leak on the early `dma_map_sgtable` error paths by replacing `kfree(rxd)` with `sa_free_sa_rx_data(rxd)`. However, the fix addresses a non-existent leak and is functionally a no-op.\",\"locations\":[{\"code_snippet\":\"\\t\\t\\tsa_free_sa_rx_data(rxd);\\n\\t\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1134,\"why_this_location_matters\":\"This is the primary location modified by the patch which acts identically to the replaced `kfree(rxd)` because no earlier mapping actually exists.\"},{\"code_snippet\":\"\\t\\t\\tsa_free_sa_rx_data(rxd);\\n\\t\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1145,\"why_this_location_matters\":\"This is the secondary location modified by the patch which also acts identically to the replaced `kfree(rxd)`.\"}],\"reasoning\":\"The modified error paths handle failures from the very first `dma_map_sgtable()` calls in `sa_run()` (mapped_sg[0]). At this point, `rxd` has just been allocated via `kzalloc_obj()`, and no prior mappings exist (`mapped_sg[0].mapped` is strictly false). If `dma_map_sgtable()` fails, it internally cleans up any partial state and returns an error, leaving `mapped` as false. Consequently, when `sa_free_sa_rx_data(rxd)` is called, the loop checking `mapped_sg->mapped` is entirely skipped, and the function just executes `kfree(rxd)`—exactly as the baseline code did. There was no leak to begin with, and this patch does not alter the actual runtime behavior, making it a placebo fix for a hallucinated bug. It is completely safe, however.\",\"type\":\"Ineffective Fix / Placebo\"}],\"dismissed_concerns_count\":1,\"findings\":[]}","patch_id":189881,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":1147648,"tokens_in":1857844,"tokens_out":16664},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466737,"id":167775,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":0,\"dismissed_concerns\":[{\"description\":\"Changing `ad.iv_idx` from 6 to 4 in `sa_3des_cbc_setkey` might cause the RX DMA callback to read the wrong IV or read out-of-bounds metadata.\",\"locations\":[{\"code_snippet\":\"ad.iv_idx = 4;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_3des_cbc_setkey\",\"line\":959,\"why_this_location_matters\":\"This modifies the expected location of the returned IV in the RX metadata descriptor.\"},{\"code_snippet\":\"req->mdata_size = sa_prepare_tx_desc(mdptr, sa_ctx->cmdl_size,\\n\\t\\t\\t\\t\\t     cmdl, sizeof(sa_ctx->epib),\\n\\t\\t\\t\\t\\t     sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1234,\"why_this_location_matters\":\"This dynamically sets the accurate metadata length, preventing the hardware from shifting the returned IV.\"}],\"reasoning\":\"Prior to this patch, `mdata_size` for 3DES CBC was hardcoded to 44 bytes, even though its actual command label (`cmdl_size`) is only 16 bytes. Because `sa_prepare_tx_desc` appended `SA_PSDATA_CTX_WORDS` (including `req->type`), 8 extra bytes of garbage were sent to the SA2UL hardware. The hardware parsed this padding, which inadvertently shifted its output IV by 2 words (8 bytes). Thus, `iv_idx` was previously hacked to 6. By dynamically calculating `mdata_size` to exactly 36 bytes (16 bytes EPIB + 4 bytes mdptr[4] + 16 bytes cmdl) and removing the garbage words, the hardware now returns the IV at the standard offset `mdptr[4]`, matching AES CBC. Changing `iv_idx` to 4 is the necessary and correct fix.\",\"stage\":\"goal\",\"type\":\"Logic Error\"},{\"description\":\"Removing `SA_PSDATA_CTX_WORDS` and the appending of `req->type` to the command label might break request tracking in the RX DMA callback.\",\"locations\":[{\"code_snippet\":\"/* Removed req->type appending block */\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1099,\"why_this_location_matters\":\"This is where the context appending was removed. It is proven to be dead code as no RX path relies on it.\"}],\"reasoning\":\"The RX DMA callbacks (e.g., `sa_aes_dma_in_callback`) do not parse the request context or `req->type` from the hardware-returned metadata. Instead, they use the `rxd` parameter passed via `tx_in->callback_param`, which already holds a valid pointer to the request (`rxd->req`). Writing `req->type` to the end of the command label was dead code that only served to corrupt the hardware engine state on algorithms with shorter command labels.\",\"stage\":\"goal\",\"type\":\"Context Tracking\"},{\"description\":\"Possible incorrect `iv_idx` update for 3DES CBC from 6 to 4.\",\"locations\":[{\"code_snippet\":\"ad.iv_idx = 4;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_3des_cbc_setkey\",\"line\":959,\"why_this_location_matters\":\"This is where the 3DES CBC IV read index was updated from 6 to 4 to account for the dynamic metadata length.\"}],\"reasoning\":\"Before this patch, `sa_cipher_run()` hardcoded `sa_req.mdata_size = 44` for all skcipher operations. For AES CBC, the command label size is exactly 24 bytes, which perfectly aligned with the 44 bytes sent to the DMA (16 bytes EPIB + 4 bytes padding + 24 bytes PSDATA). For 3DES CBC, the command label size is only 16 bytes, but 44 bytes were still sent, causing 8 extra bytes of padding (including the now-removed `SA_PSDATA_CTX_WORDS`) to be appended to the PSDATA. Because the hardware was fed a 24-byte PSDATA buffer for a 16-byte command, it returned the output 8-byte IV shifted by 8 bytes, landing it at `mdptr[6..7]`. Thus, `iv_idx = 6` was required to read the shifted IV.\\n\\nBy dynamically calculating `mdata_size` based on the actual algorithm (which correctly resolves to 36 bytes for 3DES CBC), the PSDATA sent is exactly 16 bytes. The hardware now places the output IV at the correct, unshifted position at the beginning of the returned PSDATA (`mdptr[4..5]`), matching AES CBC's starting offset. Thus, changing `iv_idx` to 4 for 3DES CBC is mathematically correct and accurately realigns the index to account for the removed padding.\",\"stage\":\"implementation\",\"type\":\"Logic Verification\"},{\"description\":\"Potential buffer overflow when writing to `mdptr` in `sa_prepare_tx_desc` without verifying the maximum length (`ml`) provided by the DMA engine.\",\"locations\":[{\"code_snippet\":\"for (out = &mdptr[5], in = psdata, i = 0;\\n     i < pslen / sizeof(u32); i++)\\n\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1032,\"why_this_location_matters\":\"This is where the copy to the DMA engine's metadata buffer occurs without an explicit bounds check against `ml`.\"}],\"reasoning\":\"The function `sa_prepare_tx_desc` copies `epiblen + 4 + pslen` bytes into `mdptr`, which is allocated by the DMA engine via `dmaengine_desc_get_metadata_ptr()`. Although `ml` (max length) is returned, the driver doesn't explicitly check if `ml` is large enough, which could theoretically cause an out-of-bounds write. However, this is a pre-existing missing check in the driver. More importantly, this patch actually *reduces* the amount of data written to `mdptr` by omitting 16 bytes of obsolete context data (`SA_PSDATA_CTX_WORDS`). If the DMA engine's buffer was large enough before, it is definitely large enough now.\",\"stage\":\"execution-flow\",\"type\":\"Buffer Overflow\"},{\"description\":\"The Rx metadata index `ad.iv_idx` for 3DES CBC was reduced from 6 to 4, which could potentially read the IV from the wrong offset or out of bounds.\",\"locations\":[{\"code_snippet\":\"ad.iv_idx = 4;\\nad.iv_out_size = 8;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_3des_cbc_setkey\",\"line\":959,\"why_this_location_matters\":\"This shows the deliberate shift of the IV extraction index in Rx to match the removed padding in the Tx packet.\"}],\"reasoning\":\"Before the patch, 3DES CBC transmitted 6 words of `psdata` (16 bytes of command label + 8 bytes of padded legacy context) due to `mdata_size` being statically set to 44 bytes. The hardware would return the metadata and output the IV at index 6. With this patch, the legacy context is removed and `mdata_size` is calculated dynamically (dropping down to 36 bytes for 3DES CBC). As a result, the hardware receives a shorter command, meaning it outputs the IV 2 words earlier in the metadata. The index change from 6 to 4 accurately aligns with the new layout, matching the behavior of AES CBC. The read falls safely within the bounds of the returned Rx metadata.\",\"stage\":\"execution-flow\",\"type\":\"Logic Error\"},{\"description\":\"Possible memory leak of scatterlist (split_sg) allocated by sg_split on DMA preparation error path.\",\"locations\":[{\"code_snippet\":\"\\t\\tret = -EINVAL;\\n\\t\\tgoto err_cleanup;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1222,\"why_this_location_matters\":\"This is the error path triggered if DMA tx_out preparation fails after split_sg was potentially allocated.\"}],\"reasoning\":\"When processing scatterlists in sa_run(), if sg_split() is invoked, it dynamically allocates memory which is stored in mapped_sg->split_sg. If a subsequent dmaengine_prep_slave_sg() call fails, execution jumps to the err_cleanup label. While sa_run() does not explicitly free split_sg directly on this path, it calls sa_free_sa_rx_data(rxd). Investigating this cleanup function shows that it safely iterates through the mapped_sg elements and calls kfree(mapped_sg->split_sg) if mapped_sg->mapped is true. Thus, the memory is correctly cleaned up.\",\"stage\":\"resources\",\"type\":\"Memory Leak\"},{\"description\":\"Potential disclosure of uninitialized stack memory to DMA engine from the local cmdl array.\",\"locations\":[{\"code_snippet\":\"\\treq->mdata_size = sa_prepare_tx_desc(mdptr, sa_ctx->cmdl_size,\\n\\t\\t\\t\\t\\t     cmdl, sizeof(sa_ctx->epib),\\n\\t\\t\\t\\t\\t     sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1234,\"why_this_location_matters\":\"This call explicitly defines the read bounds for the locally allocated cmdl stack array, proving it matches the initialized size exactly.\"}],\"reasoning\":\"In sa_run(), the local u32 cmdl[SA_MAX_CMDL_WORDS] array is sized to 96 bytes (24 words). Only sa_ctx->cmdl_size bytes are initialized via memcpy() from the pre-generated context. sa_prepare_tx_desc() subsequently reads from this array to populate the DMA hardware descriptor's metadata. However, because the pslen parameter passed to sa_prepare_tx_desc() is exactly sa_ctx->cmdl_size, the loop (i < pslen / sizeof(u32)) only accesses the explicitly initialized bytes. It never accesses the uninitialized remainder of the stack array, eliminating the risk of an uninitialized memory disclosure.\",\"stage\":\"resources\",\"type\":\"Uninitialized Variable\"},{\"description\":\"The return value of dmaengine_desc_get_metadata_ptr() is directly cast and written to by sa_prepare_tx_desc() without checking for NULL or ERR_PTR.\",\"locations\":[{\"code_snippet\":\"mdptr = (u32 *)dmaengine_desc_get_metadata_ptr(tx_out, &pl, &ml);\\n\\nreq->mdata_size = sa_prepare_tx_desc(mdptr, sa_ctx->cmdl_size,\\n\\t\\t\\t\\t     cmdl, sizeof(sa_ctx->epib),\\n\\t\\t\\t\\t     sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1234,\"why_this_location_matters\":\"This is where the potentially invalid metadata pointer is retrieved and immediately passed to a function that blindly writes to it.\"}],\"reasoning\":\"The ti/k3-udma DMA engine can return ERR_PTR(-ENOTSUPP) if the channel is not configured for packet mode or lacks a metadata_size. However, this configuration is statically defined via the Device Tree and requested during driver probe. A misconfiguration would cause a kernel panic on the first crypto operation, but it is an administrative/hardware configuration error rather than an attacker-triggerable security vulnerability. There is no user-controlled input that can force the DMA engine to fail metadata retrieval mid-operation.\",\"stage\":\"security\",\"type\":\"Null/Invalid Pointer Dereference\"},{\"description\":\"The dynamically calculated req->mdata_size could potentially exceed the metadata buffer capacity (ml) provided by the DMA engine, leading to an out-of-bounds write in sa_prepare_tx_desc().\",\"locations\":[{\"code_snippet\":\"for (out = &mdptr[5], in = psdata, i = 0;\\n     i < pslen / sizeof(u32); i++)\\n\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1041,\"why_this_location_matters\":\"This loop writes the dynamically sized cmdl array into the DMA hardware's memory-mapped metadata buffer.\"}],\"reasoning\":\"The driver does not explicitly check if `req->mdata_size <= ml` before copying data. However, `req->mdata_size` evaluates strictly to `20 + cmdl_size`. The `cmdl_size` is calculated during the algorithm's `setkey` phase and is bounded by fixed cryptographic algorithm parameters (e.g., maximum IV sizes of 16 bytes for AES). For all supported algorithms (AES, 3DES, SHA, AEAD), the maximum `cmdl_size` is 32 bytes (used in AEAD). This results in a maximum write of 52 bytes, which securely fits within the standard 64-byte CPPI5 hardware metadata descriptor limit. Because these parameters are tied strictly to the algorithm choice and cannot be inflated by user-space length manipulation, there is no exploitable buffer overflow. In fact, this patch actually fixes a pre-existing issue where the driver was unconditionally padding the `pslen` with 16 extra bytes (leading to a 68-byte write for AEAD) that silently overflowed the 64-byte descriptor buffer.\",\"stage\":\"security\",\"type\":\"Buffer Overflow\"},{\"description\":\"Potential incorrect IV read index for 3DES CBC due to ad.iv_idx changing from 6 to 4.\",\"locations\":[{\"code_snippet\":\"ad.iv_idx = 4;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_3des_cbc_setkey\",\"line\":959,\"why_this_location_matters\":\"This is where the Rx IV index offset for 3DES is updated to match the dynamically sized, unpadded hardware metadata.\"}],\"reasoning\":\"At first glance, changing `ad.iv_idx` from 6 to 4 for 3DES seems like it would cause the driver to read the wrong bytes from the Rx DMA metadata (`mdptr[4..5]` instead of `mdptr[6..7]`). However, the patch also changes `req->mdata_size` to be dynamically calculated based on actual `cmdl_size`. For 3DES, the hardcoded `mdata_size` of 44 bytes incorrectly padded the Tx metadata to 24 bytes of PSDATA, causing the SA2UL hardware to evict the 8-byte IV at the end of the padded 24-byte payload (which fell into words 6 and 7). By removing the unused context words and dynamically setting `mdata_size` to 36 bytes (16 bytes PSDATA), the hardware correctly evicts the 3DES IV at bytes 8-15 of the PSDATA, which perfectly maps to `mdptr[4..5]` in Rx. Thus, updating `iv_idx` to 4 is correct and fixes the index alignment.\",\"stage\":\"hardware\",\"type\":\"Hardware State / DMA Metadata\"},{\"description\":\"Potential out-of-bounds read when preparing DMA metadata in sa_prepare_tx_desc.\",\"locations\":[{\"code_snippet\":\"for (out = &mdptr[5], in = psdata, i = 0;\\n     i < pslen / sizeof(u32); i++)\\n\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1041,\"why_this_location_matters\":\"This is where the command label is copied to the DMA engine's metadata buffer, proving no out-of-bounds memory access occurs with the newly sized arrays.\"}],\"reasoning\":\"The function copies `pslen` bytes from the local `cmdl` stack array to the DMA descriptor metadata buffer. Since `pslen` (which corresponds to `sa_ctx->cmdl_size`) could theoretically exceed the size of the `cmdl` array if the algorithm demands a large command label, this could cause a buffer overflow. However, the patch also increases `SA_MAX_CMDL_WORDS` from 12 to 24, which ensures the `cmdl` stack array is 96 bytes long. The maximum `cmdl_size` generated across all algorithms is 32 bytes (for AEAD). Thus, the `memcpy` and subsequent reads are perfectly safe and within bounds.\",\"stage\":\"hardware\",\"type\":\"Buffer Overflow\"}],\"dismissed_concerns_count\":11,\"findings\":[]}","patch_id":189883,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":3099610,"tokens_in":4015590,"tokens_out":10293},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466740,"id":167776,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The patch's attempt to fix a concurrent setkey() race by snapshotting `cmdl_size` and `cmdl_upd_info` is incomplete and flawed. It relies on non-atomic copies without barriers and leaves critical arrays and DMA memory exposed to lockless in-place mutations.\",\"locations\":[{\"code_snippet\":\"cmdl_upd_info = sa_ctx->cmdl_upd_info;\\nmemcpy(cmdl, sa_ctx->cmdl, cmdl_size);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1102,\"why_this_location_matters\":\"This is where the non-atomic struct copy and lockless buffer read occur, failing to prevent the data race with setkey().\"},{\"code_snippet\":\"req->mdata_size = sa_prepare_tx_desc(mdptr, cmdl_size, cmdl, sizeof(sa_ctx->epib), sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1239,\"why_this_location_matters\":\"sa_ctx->epib is passed directly to the descriptor prep function, unprotected from concurrent modification by setkey().\"},{\"code_snippet\":\"memzero_explicit(sc_buf, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":692,\"why_this_location_matters\":\"This zeroes the DMA-mapped hardware context (ctx->sc) in place, which will catastrophically corrupt any in-flight hardware requests using the old key.\"},{\"code_snippet\":\"memzero_explicit(cmdl, (SA_MAX_CMDL_WORDS * sizeof(u32)));\\nmemzero_explicit(upd_info, sizeof(*upd_info));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_format_cmdl_gen\",\"line\":545,\"why_this_location_matters\":\"This is where the concurrent setkey() zeroes the shared state, creating the torn/corrupted state that sa_run() can read.\"}],\"patch_index\":20,\"patch_subject\":\"[PATCH 20/30] crypto: sa2ul - fix command label stack corruption\",\"preexisting\":true,\"reasoning\":\"1. The patch snapshots `cmdl_size` and `cmdl_upd_info` without synchronization (e.g., spinlocks or RCU) or compiler barriers. The struct assignment `cmdl_upd_info = sa_ctx->cmdl_upd_info` is non-atomic and may be torn, or completely elided by the compiler since `sa_update_cmdl` is inline.\\n2. The patch continues to locklessly copy the `cmdl` array via `memcpy(cmdl, sa_ctx->cmdl, cmdl_size)`. Concurrently, `setkey()` calls `sa_format_cmdl_gen()` which zeroes the array via `memzero_explicit()`, causing `memcpy` to read a torn or partially zeroed array.\\n3. `sa_ctx->epib` is completely omitted from the snapshot and passed directly to `sa_prepare_tx_desc()` locklessly, while `setkey()` mutates it concurrently via `sa_set_swinfo()`.\\n4. Crucially, `setkey()` calls `sa_init_sc()`, which performs `memzero_explicit(ctx->sc, SA_CTX_MAX_SZ)`. This zeroes the DMA-mapped hardware context actively being used by the hardware for in-flight requests, causing hardware faults or silent data corruption.\\n5. True isolation against a concurrent `setkey()` requires allocating a new context and retiring the old one via RCU, or protecting the shared state with a lock, rather than non-atomic field copies.\",\"type\":\"Concurrency / Incomplete Fix\"}],\"concerns_count\":7,\"dismissed_concerns\":[{\"description\":\"Compiler reloading cmdl_size or concurrent updates could cause sa_prepare_tx_desc() to read uninitialized stack memory from cmdl.\",\"locations\":[{\"code_snippet\":\"cmdl_size = sa_ctx->cmdl_size;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1101,\"why_this_location_matters\":\"This assignment lacks a READ_ONCE(), theoretically allowing the compiler to reload the variable later, but is safe due to parameter determinism.\"},{\"code_snippet\":\"req->mdata_size = sa_prepare_tx_desc(mdptr, cmdl_size, cmdl, sizeof(sa_ctx->epib), sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1239,\"why_this_location_matters\":\"This is where a reloaded, larger cmdl_size would cause reading past the initialized portion of the cmdl stack array.\"}],\"reasoning\":\"Before the patch, a concurrent setkey() could cause sa_ctx->cmdl_size to be read as different values for memcpy() and sa_prepare_tx_desc(), exposing uninitialized stack memory. The patch fixes this by snapshotting cmdl_size. While the local variable assignment lacks READ_ONCE(), theoretically allowing compiler reloading, trace analysis shows cmdl_size is strictly deterministic based on fixed TFM parameters (like iv_size). It never changes across setkey() calls for the same TFM, making compiler reloads harmless.\",\"type\":\"Out-of-bounds Read / Uninitialized Memory\"},{\"description\":\"Memory leak of rxd->tx_in DMA descriptor if sa_run fails during tx_out preparation.\",\"locations\":[{\"code_snippet\":\"\\ttx_out = dmaengine_prep_slave_sg(pdata->dma_tx, src,\\n\\t\\t\\t\\t\\t src_nents, DMA_MEM_TO_DEV,\\n\\t\\t\\t\\t\\t DMA_PREP_INTERRUPT | DMA_CTRL_ACK);\\n\\n\\tif (!tx_out) {\\n\\t\\tdev_err(pdata->dev, \\\"OUT prep_slave_sg() failed\\\\n\\\");\\n\\t\\tret = -EINVAL;\\n\\t\\tgoto err_cleanup;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1228,\"why_this_location_matters\":\"This error path bypasses descriptor submission, which is safely handled by the DMA framework's channel teardown rather than requiring manual freeing of the descriptor.\"}],\"reasoning\":\"If dmaengine_prep_slave_sg() fails for tx_out, the previously prepared rxd->tx_in descriptor is not explicitly freed or submitted. However, this is not a leak because DMA engine drivers manage unsubmitted prepared descriptors within the channel lifecycle, recycling or cleaning them up upon channel termination. The callback is also not invoked for unsubmitted descriptors.\",\"type\":\"Resource Management\"},{\"description\":\"Possible stack buffer overflow in `sa_update_cmdl` due to a torn read of `cmdl_upd_info` from `sa_ctx->cmdl_upd_info` during a concurrent `setkey()`.\",\"locations\":[{\"code_snippet\":\"cmdl[upd_info->enc_size.index] &= ~SA_CMDL_PAYLOAD_LENGTH_MASK;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":619,\"why_this_location_matters\":\"This is where the potentially torn index value is used to access the stack array.\"},{\"code_snippet\":\"cmdl_upd_info = sa_ctx->cmdl_upd_info;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1102,\"why_this_location_matters\":\"This struct assignment is the source of the torn read when executed concurrently with setkey().\"}],\"reasoning\":\"The commit isolates `cmdl_upd_info` because reading it concurrently with `setkey()` (which calls `memzero_explicit` and `sa_format_cmdl_gen`) leads to a torn read. If a torn read of the `u16 index` fields resulted in a wild value, `sa_update_cmdl()` could write out of bounds of the 24-word `cmdl` stack array. However, `sa_format_cmdl_gen` only writes zero or small integer values (< 24) to these index fields. Since both the old and new values have a zero high byte, any combination of bytes from a torn read will also have a zero high byte, keeping the resulting integer extremely small (< 24). This prevents any stack buffer overflow, limiting the impact to logical corruption of the crypto packet.\",\"type\":\"Stack Buffer Overflow\"},{\"description\":\"Potential out-of-bounds write to the DMA descriptor metadata buffer in `sa_prepare_tx_desc` due to concurrent update of `cmdl_size`.\",\"locations\":[{\"code_snippet\":\"for (out = &mdptr[5], in = psdata, i = 0;\\n\\t     i < pslen / sizeof(u32); i++)\\n\\t\\t*out++ = *in++;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_tx_desc\",\"line\":1042,\"why_this_location_matters\":\"This loop copies data into the metadata buffer based on the concurrently updated size.\"},{\"code_snippet\":\"req->mdata_size = sa_prepare_tx_desc(mdptr, cmdl_size,\\n\\t\\t\\t\\t\\t     cmdl, sizeof(sa_ctx->epib),\\n\\t\\t\\t\\t\\t     sa_ctx->epib);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1239,\"why_this_location_matters\":\"This is where the snapshot `cmdl_size` is passed to the copy routine.\"}],\"reasoning\":\"`sa_run` reads `sa_ctx->cmdl_size` concurrently with `setkey()`. This size is then used in `sa_prepare_tx_desc` to copy `pslen / sizeof(u32)` words into `mdptr`. However, `setkey` validates that the new `cmdl_size` is strictly bounded (`<= SA_MAX_CMDL_WORDS * sizeof(u32)`, which is 96). The underlying DMA engine driver guarantees that the allocated metadata buffer is large enough to accommodate the maximum context sizes required by the hardware. Thus, an artificially enlarged `cmdl_size` cannot be injected to overflow the DMA metadata buffer.\",\"type\":\"Buffer Overflow\"}],\"dismissed_concerns_count\":4,\"findings\":[]}","patch_id":189890,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2408532,"tokens_in":3114657,"tokens_out":19676},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466775,"id":167777,"inline_review":"commit f82c094f5e4721dc082e4e39d4098e73b1585323\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - fix error handling in sa_prepare_iopad\n\nThis commit modifies sa_prepare_iopads and sa_export_shash to start\nreturning errors in case of failures. The errors are now properly propagated\nup the call stack.\n\n> diff --git a/drivers/crypto/sa2ul.c b/drivers/crypto/sa2ul.c\n> index 9e86b9531366d..f89e84c5529b9 100644\n> --- a/drivers/crypto/sa2ul.c\n> +++ b/drivers/crypto/sa2ul.c\n[ ... ]\n> @@ -435,18 +445,49 @@ static void sa_prepare_iopads(struct algo_data *data, const u8 *key,\n>  \n>  \tprepare_kipad(sha.k_pad, key, key_sz);\n>  \n> -\tcrypto_shash_init(shash);\n> -\tcrypto_shash_update(shash, sha.k_pad, block_size);\n> -\tsa_export_shash(&sha, shash, digest_size, ipad);\n> +\tret = crypto_shash_init(shash);\n> +\tif (ret) {\n> +\t\tdev_err(sa_k3_dev, \"%s: %d: crypto_shash_init for ipad failed, ret=%d\\n\",\n> +\t\t\t__func__, __LINE__, ret);\n> +\t\treturn ret;\n> +\t}\n\n[Severity: Medium]\nWhen crypto_shash_init() fails, does this early return skip explicitly zeroing\nthe sensitive key material in the local 'sha' union?\n\nIt looks like this newly added error path, as well as the other early returns\nfor crypto_shash_update() and sa_export_shash(), bypass the memzero_explicit()\ncall at the end of the function. This could leave sensitive cryptographic key\nmaterial unzeroed on the kernel stack.\n\n> +\tret = crypto_shash_update(shash, sha.k_pad, block_size);\n> +\tif (ret) {\n> +\t\tdev_err(sa_k3_dev, \"%s: %d: crypto_shash_update for ipad failed, ret=%d\\n\",\n> +\t\t\t__func__, __LINE__, ret);\n> +\t\treturn ret;\n> +\t}\n[ ... ]\n>  \tmemzero_explicit(&sha, sizeof(sha));\n> +\n> +\treturn ret;\n>  }","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":7,\"dismissed_concerns\":[{\"description\":\"Possible memory leak or persistent exposure of the encryption key in the security context buffer (`sc_buf`) if `sa_init_sc()` fails.\",\"locations\":[{\"code_snippet\":\"\\t\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":784,\"why_this_location_matters\":\"This is where sa_init_sc returns an error after writing the encryption key, abandoning initialization of the DMA buffer midway.\"},{\"code_snippet\":\"\\tsa_free_ctx_info(&ctx->enc, data);\\n\\tsa_free_ctx_info(&ctx->dec, data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_exit_tfm_aead\",\"line\":1768,\"why_this_location_matters\":\"This proves that the driver's exit function correctly cleans up the DMA buffers initialized/partially initialized for both contexts when the crypto subsystem breaks down the failed transform.\"}],\"reasoning\":\"While `sa_init_sc()` partially populates `sc_buf` (including the encryption key) and then aborts without zeroing it if `sa_set_sc_auth()` fails, `sc_buf` is part of the persistent TFM context allocated during initialization. The crypto framework manages this teardown gracefully. When `setkey()` fails, the framework calls the transform's exit function (`sa_exit_tfm_aead()`), which executes `sa_free_ctx_info()`. This explicitly zeroizes `ctx->sc` with `memzero_explicit()` before unmapping and freeing the DMA pool memory. No leak or key exposure occurs.\",\"type\":\"Resource Management\"},{\"description\":\"Possible memory leak of `shash` descriptor in `sa_prepare_iopads()` if crypto functions fail.\",\"locations\":[{\"code_snippet\":\"\\tSHASH_DESC_ON_STACK(shash, data->ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":427,\"why_this_location_matters\":\"This macro confirms that the descriptor allocation is constrained to the stack, making an early return safe from a dynamic memory leak perspective.\"}],\"reasoning\":\"Because `sa_prepare_iopads()` now returns early on error, it bypasses explicit teardowns. However, `shash` is initialized using the `SHASH_DESC_ON_STACK` macro, which allocates the hash descriptor securely on the stack rather than dynamically on the heap. Therefore, an early return correctly adjusts the stack pointer and will not cause a dynamic memory leak.\",\"type\":\"Memory Leak\"},{\"description\":\"Possible uninitialized variable usage when returning `ret` in `sa_export_shash()`.\",\"locations\":[{\"code_snippet\":\"\\tint ret = 0;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":401,\"why_this_location_matters\":\"Initialization of `ret` ensures no garbage values are returned if the function completes successfully.\"}],\"reasoning\":\"`ret` is correctly initialized to 0 and reassigned by `crypto_shash_export()`. If the export fails, it returns the error code; if it succeeds, it proceeds and correctly returns the success code (0). There is no path where an uninitialized `ret` is returned.\",\"type\":\"Resource Management\"},{\"description\":\"Concurrent setkey operations could cause a data race on `sc_buf` during `sa_init_sc()`.\",\"locations\":[{\"code_snippet\":\"\\t\\tret = sa_set_sc_auth(ad, auth_key, auth_key_sz,\\n\\t\\t\\t\\t     &sc_buf[auth_sc_offset]);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":781,\"why_this_location_matters\":\"This is the point of context buffer modification that appears unlocked but is implicitly protected by the subsystem design.\"}],\"reasoning\":\"`sa_init_sc()` modifies the TFM-specific security context buffer (`sc_buf`). While no driver-level lock is acquired in this path, the crypto API guarantees that `.setkey` callbacks (like `sa_aead_setkey`) are strictly serialized per TFM by the crypto core, or are only called during initialization before the TFM object is fully exposed to consumers. Concurrent executions on the same context are prevented at a higher level.\",\"type\":\"Race Condition / Missing Locking\"},{\"description\":\"Stack buffer overflow if an underlying hardware hash provider exports state larger than the `sha` union size.\",\"locations\":[{\"code_snippet\":\"\\tret = crypto_shash_export(hash, state);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":418,\"why_this_location_matters\":\"The location where the provider's state is exported into the fixed-size stack variable.\"}],\"reasoning\":\"`sa_export_shash` calls `crypto_shash_export()` targeting a stack union sized for standard SHA1 and SHA256 software states. The Linux crypto API explicitly mandates that all providers of standard hashes (like `sha1`, `sha256`) must use the standard state structures (`struct sha1_state`, etc.) for their export layout to guarantee interchangeability. Therefore, `crypto_shash_export()` is guaranteed not to exceed the size of the stack union.\",\"type\":\"Memory Corruption\"},{\"description\":\"Potential uninitialized memory usage for `ipad` and `opad` in the security context if `sa_export_shash()` fails.\",\"locations\":[{\"code_snippet\":\"\\tret = crypto_shash_export(hash, state);\\n\\tif (ret) {\\n\\t\\tdev_err(sa_k3_dev, \\\"%s: crypto_shash_export failed\\\\n\\\",\\n\\t\\t\\t__func__);\\n\\t\\treturn ret;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":420,\"why_this_location_matters\":\"This is where the function returns early without writing to the `out` parameter, safely propagating the error.\"}],\"reasoning\":\"If `sa_export_shash()` fails, it returns early without populating the `out` buffer (which points to `ipad` or `opad`). However, this error is appropriately propagated through `sa_prepare_iopads()` and `sa_set_sc_auth()` back up to the initialization routine `sa_init_sc()`. Since `sa_init_sc()` aborts and returns an error to its caller, the unpopulated security context buffer is discarded and never used for active cryptographic operations.\",\"type\":\"Uninitialized Memory Usage\"}],\"dismissed_concerns_count\":6,\"findings\":[{\"locations\":[{\"code_snippet\":\"\\tret = crypto_shash_init(shash);\\n\\tif (ret) {\\n\\t\\tdev_err(sa_k3_dev, \\\"%s: %d: crypto_shash_init for ipad failed, ret=%d\\\\n\\\",\\n\\t\\t\\t__func__, __LINE__, ret);\\n\\t\\treturn ret;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":448,\"why_this_location_matters\":\"This is the first of several newly introduced early error returns that completely skip the explicit zeroing of sensitive memory.\"},{\"code_snippet\":\"\\tmemzero_explicit(&sha, sizeof(sha));\\n\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":490,\"why_this_location_matters\":\"This explicit memory clearing step is now bypassed on all newly introduced error paths.\"}],\"patch_index\":21,\"patch_subject\":\"[PATCH 21/30] crypto: sa2ul - fix error handling in sa_prepare_iopad\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: unzeroed key material on stack in sa_prepare_iopads() error paths\",\"severity\":\"Medium\",\"severity_explanation\":\"1. Consequence: Sensitive cryptographic key material (HMAC derived pads) is left unzeroed in kernel stack memory, violating subsystem requirements to explicitly zeroize keys after use.\\n2. Triggering path: If `crypto_shash_init()`, `crypto_shash_update()`, or `sa_export_shash()` fail, the newly added error paths return early, bypassing the explicit memory zeroing at the end of the function.\\n3. Reachability: This occurs on cold error paths during crypto context setup. Although follow-up patch 'crypto: sa2ul - fix stack overflow in sa_prepare_iopads' refactors the stack variables to use `k_ipad` and `k_opad`, the early return bug persists through the end of the series, continuing to skip explicit zeroing on error paths.\"}]}","patch_id":189882,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":696386,"tokens_in":1193934,"tokens_out":13097},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466795,"id":167778,"inline_review":"commit 55fdb96deaeb9f257c9c212ea097920a92bfba10\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - move export to appropriate location.\n    \nThe current code just writes ipad/opad into the sa2ul context but SA2UL\nrequires the intermediate digest to be programmed into it. Export the\nintermediate hash state before big endian processing to program the\ncorrect state in SA2UL.\n\n> diff --git a/drivers/crypto/sa2ul.c b/drivers/crypto/sa2ul.c\n> index f89e84c5529b9..36c8403b5713c 100644\n> --- a/drivers/crypto/sa2ul.c\n> +++ b/drivers/crypto/sa2ul.c\n> @@ -400,6 +400,14 @@ static int sa_export_shash(void *state, struct shash_desc *hash,\n>  \tu32 *result;\n>  \tint ret = 0;\n>  \n> +\t/* Export the intermediate digest to program into SA2UL */\n> +\tret = crypto_shash_export(hash, state);\n> +\tif (ret) {\n> +\t\tdev_err(sa_k3_dev, \"%s: crypto_shash_export failed\\n\",\n> +\t\t\t__func__);\n> +\t\treturn ret;\n> +\t}\n> +\n\n[Severity: Medium]\nThis is a pre-existing issue, but does returning early on error paths in the\ncaller of this function leave sensitive key material unzeroed on the stack?\n\nLooking at sa_prepare_iopads() in drivers/crypto/sa2ul.c, which calls\nsa_export_shash():\n\ndrivers/crypto/sa2ul.c:sa_prepare_iopads() {\n    ...\n\tret = sa_export_shash(&sha, shash, digest_size, ipad);\n\tif (ret) {\n\t\tdev_err(sa_k3_dev, \"%s: %d: sa_export_shash for ipad failed, ret=%d\\n\",\n\t\t\t__func__, __LINE__, ret);\n\t\treturn ret;\n\t}\n    ...\n\tmemzero_explicit(&sha, sizeof(sha));\n\n\treturn ret;\n}\n\nIf any underlying crypto operations fail (like crypto_shash_init,\ncrypto_shash_update, or sa_export_shash), the function returns immediately.\n\nThis skips the required memzero_explicit() cleanup at the end of the function,\nleaving cryptographic key material (HMAC pads) unzeroed on the kernel stack.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Stack buffer overflow in prepare_kipad() and prepare_kopad() due to unbounded HMAC key size.\",\"locations\":[{\"code_snippet\":\"for (i = 0; i < key_sz; i++)\\n\\t\\tk_ipad[i] = key[i] ^ 0x36;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"prepare_kipad\",\"line\":375,\"why_this_location_matters\":\"Writes to the 64-byte k_ipad stack buffer up to key_sz without checking if key_sz exceeds the array boundaries.\"},{\"code_snippet\":\"prepare_kipad(sha.k_pad, key, key_sz);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":447,\"why_this_location_matters\":\"Passes the unbounded key_sz and the fixed-size 64-byte array to the vulnerable function.\"}],\"patch_index\":22,\"patch_subject\":\"[PATCH 22/30] crypto: sa2ul - move export to appropriate location.\",\"preexisting\":true,\"reasoning\":\"1. `sa_aead_setkey()` extracts the authentication key via `crypto_authenc_extractkeys()`, which allows an arbitrarily large `authkeylen`.\\n2. This `authkeylen` is passed as `key_sz` through `sa_init_sc()` down to `sa_prepare_iopads()`.\\n3. `sa_prepare_iopads()` statically allocates a 64-byte stack array `sha.k_pad[SHA1_BLOCK_SIZE]`.\\n4. `prepare_kipad()` and `prepare_kopad()` iterate up to `key_sz` and write directly to this array without bounds checking.\\n5. If a user provides an HMAC key larger than 64 bytes, it will overflow the stack array, leading to severe memory corruption. The HMAC specification dictates that keys larger than the block size must be hashed first, but this implementation fails to do so and blindly overflows the buffer.\",\"type\":\"Stack Buffer Overflow\"},{\"description\":\"crypto: sa2ul: unzeroed key material on error paths in sa_prepare_iopads()\",\"locations\":[{\"code_snippet\":\"return ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":455,\"why_this_location_matters\":\"One of multiple early returns that bypass the memzero_explicit teardown block.\"},{\"code_snippet\":\"memzero_explicit(&sha, sizeof(sha));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":492,\"why_this_location_matters\":\"The required cleanup that is skipped on error paths.\"}],\"patch_index\":22,\"patch_subject\":\"[PATCH 22/30] crypto: sa2ul - move export to appropriate location.\",\"preexisting\":true,\"reasoning\":\"1. Consequence: Cryptographic key material (HMAC pads) is left unzeroed on the kernel stack when error paths are taken, causing a sensitive data leak. This violates the cryptographic rule that keys must be zeroized after use.\\n2. Triggering path: The stack buffer is populated with derived key data. If any subsequent crypto API calls (like crypto_shash_init or crypto_shash_update) fail, the function returns immediately, skipping the required memzero_explicit() cleanup at the end of the function.\\n3. Reachability: Triggering an error path here relies on a failure in the underlying crypto subsystem (e.g., memory pressure), which limits it to a cold path and thus Medium severity.\",\"type\":\"crypto: sa2ul: unzeroed key material on error paths in sa_prepare_iopads()\"}],\"concerns_count\":7,\"dismissed_concerns\":[{\"description\":\"Candidate concern: In the pre-patch code, `cpu_to_be32_array()` read uninitialized or incorrect data because `result = sha1->state` was evaluated before `crypto_shash_export()` populated the memory.\",\"locations\":[{\"code_snippet\":\"sha1 = state;\\nresult = sha1->state;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":412,\"why_this_location_matters\":\"This pointer assignment evaluates to the base address of the state buffer, making its order relative to crypto_shash_export() irrelevant.\"}],\"reasoning\":\"This concern is invalid because C pointer semantics dictate that `result = sha1->state` merely evaluates the base address of the array (at offset 0 of the struct), not the memory contents. The memory was correctly populated by `crypto_shash_export()` before `cpu_to_be32_array()` read from it. Therefore, the pre-patch code was already correct, and the patch's reordering provides no functional benefit.\",\"type\":\"Data Corruption / Pointer Evaluation\"},{\"description\":\"Candidate concern: Moving `crypto_shash_export()` before the `digest_size` validation creates an exploitable stack buffer overflow in practice.\",\"locations\":[{\"code_snippet\":\"ret = crypto_shash_export(hash, state);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":404,\"why_this_location_matters\":\"This is the newly moved export call which now occurs before the `digest_size` validation switch block, making it a candidate for triggering a write before size verification.\"},{\"code_snippet\":\"ret = sa_export_shash(&sha, shash, digest_size, ipad);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":461,\"why_this_location_matters\":\"This caller provides the 104-byte `&sha` stack buffer that would overflow if an oversized statesize algorithm were permitted.\"}],\"reasoning\":\"While moving the export operation before the validation check creates a latent vulnerability (as it writes to the fixed-size 104-byte `state` buffer before checking if the algorithm's state size fits), this attack surface is proven unreachable in practice. The function `sa_prepare_iopads` is exclusively invoked for AEAD algorithms explicitly initialized with standard `sha1` and `sha256` primitives (via `sa_cra_init_aead_sha1` and `sa_cra_init_aead_sha256`). Consequently, the `digest_size` is rigidly constrained to 20 or 32 bytes, safely within the buffer limits.\",\"type\":\"Stack Buffer Overflow\"}],\"dismissed_concerns_count\":2,\"findings\":[{\"locations\":[{\"code_snippet\":\"return ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":455,\"why_this_location_matters\":\"One of multiple early returns that bypass the memzero_explicit teardown block.\"},{\"code_snippet\":\"memzero_explicit(&sha, sizeof(sha));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":492,\"why_this_location_matters\":\"The required cleanup that is skipped on error paths.\"}],\"patch_index\":22,\"patch_subject\":\"[PATCH 22/30] crypto: sa2ul - move export to appropriate location.\",\"preexisting\":true,\"problem\":\"crypto: sa2ul: unzeroed key material on error paths in sa_prepare_iopads()\",\"severity\":\"Medium\",\"severity_explanation\":\"1. Consequence: Cryptographic key material (HMAC pads) is left unzeroed on the kernel stack when error paths are taken, causing a sensitive data leak. This violates the cryptographic rule that keys must be zeroized after use.\\n2. Triggering path: The stack buffer is populated with derived key data. If any subsequent crypto API calls (like crypto_shash_init or crypto_shash_update) fail, the function returns immediately, skipping the required memzero_explicit() cleanup at the end of the function.\\n3. Reachability: Triggering an error path here relies on a failure in the underlying crypto subsystem (e.g., memory pressure), which limits it to a cold path and thus Medium severity.\"}]}","patch_id":189887,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":3321407,"tokens_in":4126219,"tokens_out":16666},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466797,"id":167779,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The sa_prepare_iopads() function allocates a fixed-size 64-byte array `k_pad` on the stack, but passes an unvalidated `key_sz` (derived from a user-provided authentication key length) to prepare_kipad() and prepare_kopad(). If the authentication key exceeds 64 bytes, these functions write out-of-bounds, causing a severe stack buffer overflow.\",\"locations\":[{\"code_snippet\":\"\\tfor (i = 0; i < key_sz; i++)\\n\\t\\tk_ipad[i] = key[i] ^ 0x36;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"prepare_kipad\",\"line\":376,\"why_this_location_matters\":\"This iteration continues until `key_sz`, which is attacker-controlled and unconstrained, allowing it to write out-of-bounds into the stack buffer.\"},{\"code_snippet\":\"\\tu8 k_pad[SHA1_BLOCK_SIZE];\\n\\n\\tshash->tfm = data->ctx->shash;\\n\\n\\tprepare_kipad(k_pad, key, key_sz);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":451,\"why_this_location_matters\":\"The fixed 64-byte stack allocation is the target of the overflow.\"}],\"patch_index\":23,\"patch_subject\":\"[PATCH 23/30] crypto: sa2ul - fix stack overflow in sa_prepare_iopads\",\"preexisting\":true,\"reasoning\":\"1. `crypto_authenc_extractkeys()` extracts `authkeylen` directly from the user-provided payload. This unbounded length is passed as `key_sz` into `sa_prepare_iopads()`.\\n2. `sa_prepare_iopads()` allocates `u8 k_pad[SHA1_BLOCK_SIZE]` (64 bytes) on the stack and passes it to `prepare_kipad()` and `prepare_kopad()`.\\n3. The loop `for (i = 0; i < key_sz; i++) k_ipad[i] = key[i] ^ 0x36;` blindly writes up to `key_sz` bytes. If `key_sz` exceeds 64 bytes, it overflows the stack buffer, corrupting kernel memory.\\n4. The HMAC specification requires that oversized keys be hashed down to the digest size before use, which is entirely missing here.\",\"type\":\"Stack Buffer Overflow\"},{\"description\":\"Sensitive key material and intermediate hash state are left uncleared on the stack in sa_prepare_iopads() when operations fail, and shash_desc is not zeroed even upon success.\",\"locations\":[{\"code_snippet\":\"\\tret = crypto_shash_update(shash, k_pad, block_size);\\n\\tif (ret) {\\n\\t\\tdev_err(sa_k3_dev, \\\"%s: %d: crypto_shash_update for ipad failed, ret=%d\\\\n\\\",\\n\\t\\t\\t__func__, __LINE__, ret);\\n\\t\\treturn ret;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":464,\"why_this_location_matters\":\"One of several error paths that return early without calling memzero_explicit on k_pad.\"},{\"code_snippet\":\"SHASH_DESC_ON_STACK(shash, data->ctx->shash);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":447,\"why_this_location_matters\":\"This stack-allocated hash context stores sensitive partial hash state but is never cleared before returning.\"}],\"patch_index\":23,\"patch_subject\":\"[PATCH 23/30] crypto: sa2ul - fix stack overflow in sa_prepare_iopads\",\"preexisting\":true,\"reasoning\":\"1. `k_pad` is populated with sensitive key-derived material (IPAD and OPAD) via `prepare_kipad()` and `prepare_kopad()`.\\n2. If operations like `crypto_shash_init()`, `crypto_shash_update()`, or `sa_export_shash()` fail, the function logs an error and returns immediately, bypassing the `memzero_explicit(k_pad, SHA1_BLOCK_SIZE)` cleanup at the end of the function.\\n3. Additionally, `SHASH_DESC_ON_STACK(shash, ...)` allocates the hash context on the stack. This context is populated with partial key state by `crypto_shash_update()`, but is never cleared via `shash_desc_zero()` or `memzero_explicit()` before the function returns on both success and error paths.\",\"type\":\"Information Leak\"}],\"concerns_count\":8,\"dismissed_concerns\":[{\"description\":\"Direct cast of opaque state buffer from crypto_shash_export() to `(u32 *)` might be unsafe or read out-of-bounds if the internal digest is not at offset 0, or if state_size is smaller than digest_size.\",\"locations\":[{\"code_snippet\":\"\\tcase SHA256_DIGEST_SIZE:\\n\\t\\tresult = (u32 *)sha;\\n\\t\\tbreak;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":427,\"why_this_location_matters\":\"This is where the intermediate digest state is assumed to be located at the start of the exported state buffer.\"},{\"code_snippet\":\"cpu_to_be32_array(out, result, digest_size / 4);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":435,\"why_this_location_matters\":\"Validating the structural layout and size guarantees of crypto_shash_export ensures this read is within bounds.\"}],\"reasoning\":\"The crypto API explicitly designates the output of `crypto_shash_export()` as opaque. However, for standard SHA1 and SHA256 implementations in the kernel, the state structures (`struct sha1_state` and `struct sha256_state`) guarantee that the intermediate hash chaining variables (`u32 state[...]`) are strictly located at offset 0. Furthermore, `crypto_shash_statesize()` returns the full size of this state structure, which is structurally guaranteed to encompass the `digest_size` array. Therefore, casting the dynamically allocated `sha` buffer directly to `(u32 *)` correctly and safely extracts the intermediate digest without causing an out-of-bounds read or alignment fault.\",\"type\":\"API Violation\"},{\"description\":\"kmalloc(..., GFP_KERNEL) during sa_export_shash() could potentially sleep in an atomic context if called from the fast data path.\",\"locations\":[{\"code_snippet\":\"\\tsha = kmalloc(state_size, GFP_KERNEL);\\n\\tif (!sha)\\n\\t\\treturn -ENOMEM;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":411,\"why_this_location_matters\":\"This is where the GFP_KERNEL allocation occurs, which would be illegal if the caller was running in an atomic context.\"}],\"reasoning\":\"`sa_export_shash()` is only invoked during cryptographic key setup (`sa_aead_setkey` -> `sa_init_sc` -> `sa_setup_auth_ctx` -> `sa_prepare_iopads` -> `sa_export_shash`). The `setkey` callback for AEAD is executed in process context and is permitted to sleep (e.g., via AF_ALG or XFRM netlink). The existing driver code safely uses sleepable allocations (like `dma_pool_alloc(..., GFP_KERNEL, ...)`) in this same call chain, proving it does not operate in an atomic context.\",\"type\":\"Sleeping in Atomic Context\"},{\"description\":\"Potential memory leak of the dynamically allocated `sha` buffer in sa_export_shash() on error paths.\",\"locations\":[{\"code_snippet\":\"\\t\\tkfree_sensitive(sha);\\n\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":420,\"why_this_location_matters\":\"Shows the proper resource cleanup on the error path.\"}],\"reasoning\":\"The `sha` buffer is dynamically allocated with `kmalloc()`. Every execution path where the function returns explicitly cleans up this buffer using `kfree_sensitive(sha)`. This includes the error path if `crypto_shash_export()` fails, the default case for an invalid digest size, and the successful path. Therefore, no memory leak can occur under any condition.\",\"type\":\"Memory Leak\"}],\"dismissed_concerns_count\":3,\"findings\":[]}","patch_id":189888,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":4578822,"tokens_in":6374405,"tokens_out":18165},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466826,"id":167780,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Sensitive cryptographic key material (derived HMAC keys) and the intermediate hash descriptor state are not zeroized on error paths, leaving them exposed on the kernel stack.\",\"locations\":[{\"code_snippet\":\"\\t\\tif (err)\\n\\t\\t\\treturn err;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":441,\"why_this_location_matters\":\"Returns early without clearing partially hashed key bits in k_ipad.\"},{\"code_snippet\":\"\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":461,\"why_this_location_matters\":\"Returns early without clearing fully padded key material in k_ipad and k_opad.\"},{\"code_snippet\":\"return ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":497,\"why_this_location_matters\":\"The function exits without scrubbing the `shash` descriptor via `shash_desc_zero(shash)`.\"}],\"patch_index\":24,\"patch_subject\":\"[PATCH 24/30] crypto: sa2ul - add more checks before processing ipad/opad\",\"preexisting\":true,\"reasoning\":\"1. `sa_prepare_iopads` derives intermediate HMAC keys from the provided master key and stores them in stack arrays `k_ipad` and `k_opad`.\\n2. It initializes, updates, and exports the hash state using a stack-allocated `shash` descriptor.\\n3. If any cryptographic operation (e.g., `crypto_shash_digest`, `crypto_shash_init`, `crypto_shash_update`, or `sa_export_shash`) fails, the function immediately returns the error code.\\n4. This early return skips the `memzero_explicit(k_ipad, SHA1_BLOCK_SIZE)` and `memzero_explicit(k_opad, SHA1_BLOCK_SIZE)` calls at the end of the function, leaking sensitive key material on the stack.\\n5. Furthermore, the `shash` descriptor (which accumulates intermediate hash state) is never scrubbed via `shash_desc_zero()` on either the success or error paths.\\n6. This directly violates the subsystem rule that keys must be zeroized after use.\",\"type\":\"Missing Key Zeroization\"}],\"concerns_count\":12,\"dismissed_concerns\":[{\"description\":\"Possible memory leak of allocated state buffer `sha` in `sa_export_shash` when returning early on error.\",\"locations\":[{\"code_snippet\":\"kfree_sensitive(sha);\\n\\t\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_export_shash\",\"line\":396,\"why_this_location_matters\":\"This demonstrates proper resource cleanup on the error path, disproving the candidate concern.\"}],\"reasoning\":\"The function allocates `sha` using `kmalloc`. If `crypto_shash_export` fails, it explicitly calls `kfree_sensitive(sha)` before returning the error. Similarly, if `digest_size` is invalid, it frees it. The buffer is safely and consistently freed on all exit paths, proving there is no memory leak.\",\"type\":\"Memory Leak\"},{\"description\":\"Potential integer truncation when assigning `int digest_size` to `u16 key_sz`.\",\"locations\":[{\"code_snippet\":\"\\t\\tkey_sz = digest_size;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":444,\"why_this_location_matters\":\"This is where the potentially truncating assignment occurs.\"}],\"reasoning\":\"While `digest_size` is an `int` and `key_sz` is `u16`, the maximum known digest size for supported algorithms (like SHA-512) is 64 bytes. This value safely fits within a 16-bit unsigned integer without any risk of dangerous truncation.\",\"type\":\"Integer Truncation\"},{\"description\":\"If an empty key is provided (`key_sz == 0`), `memcpy` could be called with a `NULL` key pointer.\",\"locations\":[{\"code_snippet\":\"\\t\\tmemcpy(k_ipad, key, key_sz);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":446,\"why_this_location_matters\":\"This is where the copy logic occurs when key_sz is less than or equal to block_size.\"}],\"reasoning\":\"The kernel's `crypto_authenc_extractkeys` mechanism requires a minimum length to hold the RTA structures, meaning `key` will point to a valid (albeit logically empty) section of the extracted parameters. Therefore, even if `key_sz` is 0, the pointer is guaranteed to be non-NULL.\",\"type\":\"Null Pointer Dereference\"},{\"description\":\"Possible out-of-bounds write in `crypto_shash_digest` when hashing large keys into `k_ipad`.\",\"locations\":[{\"code_snippet\":\"err = crypto_shash_digest(shash, key, key_sz, k_ipad);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":440,\"why_this_location_matters\":\"This is where the key digest is computed and written into the fixed-size array.\"}],\"reasoning\":\"The function calls `crypto_shash_digest(shash, key, key_sz, k_ipad)` which writes the hash output to `k_ipad`. Since `k_ipad` is sized `SHA1_BLOCK_SIZE` (64 bytes), a hash algorithm with a digest size larger than 64 could overflow it. However, the largest digest size currently supported in the kernel is 64 bytes (SHA-512). Furthermore, cryptographic algorithms guarantee that their digest size is always less than or equal to their block size. Thus, the digest output will safely fit within the buffer bounds.\",\"type\":\"Buffer Overflow\"},{\"description\":\"Potential uninitialized usage of `shash` in `crypto_shash_digest()`.\",\"locations\":[{\"code_snippet\":\"\\t\\terr = crypto_shash_digest(shash, key, key_sz, k_ipad);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":440,\"why_this_location_matters\":\"This is where the descriptor is passed into the hash framework; verifying that `tfm` is the only strictly required pre-initialized field confirms no uninitialized memory usage occurs.\"}],\"reasoning\":\"The macro `SHASH_DESC_ON_STACK` allocates `struct shash_desc` on the stack but does not initialize its fields. However, the function subsequently sets `shash->tfm = data->ctx->shash;`. Since `crypto_shash_digest` (and the underlying framework) only requires the `tfm` field to be populated before properly initializing the rest of the descriptor context via `crypto_shash_init`, this pattern is safe and correct.\",\"type\":\"Uninitialized Structure\"},{\"description\":\"Possible integer underflow in memset size calculation `block_size - key_sz` or uninitialized memory use on 0-length keys.\",\"locations\":[{\"code_snippet\":\"\\tmemset(k_ipad + key_sz, 0, block_size - key_sz);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":446,\"why_this_location_matters\":\"This is where the calculation occurs and would underflow if the size checks were incorrect.\"},{\"code_snippet\":\"\\t\\tkey_sz = digest_size;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_prepare_iopads\",\"line\":441,\"why_this_location_matters\":\"This assignment mathematically guarantees that key_sz <= block_size, negating the risk of underflow.\"}],\"reasoning\":\"If `key_sz > block_size`, the code explicitly hashes the key and assigns `key_sz = digest_size`. Since cryptographic hash functions always have a digest size less than or equal to their block size, `key_sz` is mathematically guaranteed to be `<= block_size` before the `memset` call, preventing any integer underflow. Additionally, if `key_sz == 0` (e.g., when FIPS is disabled), the check is false, `memcpy` safely copies 0 bytes, and `memset` safely zero-pads exactly `block_size` bytes. Thus, underflow and uninitialized memory vectors are systematically prevented.\",\"type\":\"Integer Underflow\"}],\"dismissed_concerns_count\":6,\"findings\":[]}","patch_id":189891,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2443639,"tokens_in":3255335,"tokens_out":19471},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466842,"id":167781,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":0,\"dismissed_concerns\":[{\"description\":\"Skipping CPU sync on the error path where `dma_sync_sgtable_for_cpu()` was not called could leave the CPU cache with stale data.\",\"locations\":[{\"code_snippet\":\"dma_unmap_sgtable(rxd->ddev, &mapped_sg->sgt,\\n\\t\\t\\t\\t\\t  mapped_sg->dir, DMA_ATTR_SKIP_CPU_SYNC);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_sa_rx_data\",\"line\":1061,\"why_this_location_matters\":\"This is where the unmap occurs, bypassing cache invalidation correctly for both the success and error paths.\"}],\"reasoning\":\"In `sa_run()`, if `dma_map_sgtable()` fails for one buffer, `sa_free_sa_rx_data()` unmaps the already mapped buffer(s) using `DMA_ATTR_SKIP_CPU_SYNC`. Because `sa_sync_from_device()` was never called on this error path, one might worry that the CPU cache remains stale. However, since the DMA operation was never submitted to the device, the device could not have modified the memory. Thus, the original memory contents are untouched, and skipping the CPU cache invalidation (or SWIOTLB copy-back) is perfectly safe and correctly avoids redundant operations. On the success path, the explicit sync already flushed/invalidated the buffers correctly, and avoiding a second sync during unmap prevents overwriting subsequent CPU modifications (like the appended auth tag).\",\"stage\":\"goal\",\"type\":\"Data Corruption / Stale Data\"},{\"description\":\"Potential swiotlb bounce buffer leak due to adding `DMA_ATTR_SKIP_CPU_SYNC` during `dma_unmap_sgtable`.\",\"locations\":[{\"code_snippet\":\"swiotlb_release_slots(dev, tlb_addr, pool);\",\"file\":\"kernel/dma/swiotlb.c\",\"function_or_symbol\":\"__swiotlb_tbl_unmap_single\",\"line\":1729,\"why_this_location_matters\":\"This is where swiotlb releases the buffer slots, proving that `DMA_ATTR_SKIP_CPU_SYNC` does not cause memory leaks.\"}],\"reasoning\":\"I investigated whether adding `DMA_ATTR_SKIP_CPU_SYNC` to `dma_unmap_sgtable` might prevent swiotlb bounce buffers from being freed. However, examining `__swiotlb_tbl_unmap_single` in `kernel/dma/swiotlb.c` confirms that while it skips the `swiotlb_bounce(..., DMA_FROM_DEVICE)` copy-back step, it still proceeds to call `swiotlb_release_slots`. Therefore, there is no resource leak of bounce buffer slots.\",\"stage\":\"implementation\",\"type\":\"Resource Management\"},{\"description\":\"Potential failure to sync `req->src` from the device when out-of-place (`req->src != req->dst`) buffers are used, since `sa_free_sa_rx_data` skips CPU sync for ALL mapped buffers.\",\"locations\":[{\"code_snippet\":\"mapped_sg->dir = DMA_FROM_DEVICE;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1222,\"why_this_location_matters\":\"Proves that the destination buffer is mapped appropriately as `DMA_FROM_DEVICE` during out-of-place encryption.\"},{\"code_snippet\":\"dma_sync_sgtable_for_cpu(rxd->ddev, sgt, DMA_FROM_DEVICE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1041,\"why_this_location_matters\":\"Proves that the destination buffer is explicitly synced manually, which copies back device writes.\"}],\"reasoning\":\"I verified that when `req->src != req->dst` (`diff_dst == true`), `req->src` is mapped with `DMA_TO_DEVICE`. For `DMA_TO_DEVICE` mappings, the DMA API never performs a device-to-CPU sync during unmap anyway. The explicit `sa_sync_from_device` correctly targets the `dst` buffer (mapped with `DMA_FROM_DEVICE`). Therefore, adding `DMA_ATTR_SKIP_CPU_SYNC` to the `src` buffer's unmap is a safe no-op that does not cause data loss or cache inconsistency.\",\"stage\":\"implementation\",\"type\":\"Data Corruption\"},{\"description\":\"Potential missing device-to-CPU synchronization in error paths where `sa_free_sa_rx_data()` is called without a prior `sa_sync_from_device()`.\",\"locations\":[{\"code_snippet\":\"err_cleanup:\\n\\tsa_free_sa_rx_data(rxd);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1319,\"why_this_location_matters\":\"This error path demonstrates that unmapping without sync occurs only when the DMA transaction was never submitted.\"},{\"code_snippet\":\"dma_unmap_sgtable(rxd->ddev, &mapped_sg->sgt, mapped_sg->dir, DMA_ATTR_SKIP_CPU_SYNC);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_sa_rx_data\",\"line\":1062,\"why_this_location_matters\":\"This is where the new SKIP_CPU_SYNC attribute is applied to all unmaps, including those in error paths.\"}],\"reasoning\":\"In the error paths of `sa_run()` (such as DMA descriptor preparation failure) and `dma_map_sgtable()`, `sa_free_sa_rx_data()` is invoked to clean up. Because `sa_sync_from_device()` is only called on the successful completion callback path, skipping the CPU sync on unmap in the error path could theoretically leave the CPU cache unsynchronized. However, in these error paths, the DMA transactions have not been submitted to the engine (`dmaengine_submit` has not been called). Since the device has not executed or modified the buffer, there are no device modifications to sync back. Furthermore, if swiotlb (bounce buffers) were used, skipping the CPU sync correctly prevents `swiotlb_bounce()` from overwriting the original CPU memory with uninitialized bounce buffer contents. Thus, using `DMA_ATTR_SKIP_CPU_SYNC` during these error paths is completely safe and actually prevents unintended memory corruption.\",\"stage\":\"execution-flow\",\"type\":\"Cache Coherency / Data Loss\"},{\"description\":\"Missing explicit CPU sync for the `DMA_TO_DEVICE` scatterlist before unmapping.\",\"locations\":[{\"code_snippet\":\"if (rxd->mapped_sg[0].dir == DMA_BIDIRECTIONAL)\\n\\t\\tsgt = &rxd->mapped_sg[0].sgt;\\n\\telse\\n\\t\\tsgt = &rxd->mapped_sg[1].sgt;\\n\\tdma_sync_sgtable_for_cpu(rxd->ddev, sgt, DMA_FROM_DEVICE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1045,\"why_this_location_matters\":\"This demonstrates that only the receive/bidirectional scatterlist is synced, intentionally leaving the transmit-only scatterlist untouched.\"}],\"reasoning\":\"When `req->src != req->dst`, the driver maps `mapped_sg[0]` as `DMA_TO_DEVICE` and `mapped_sg[1]` as `DMA_FROM_DEVICE`. The explicit sync in `sa_sync_from_device()` exclusively targets the `DMA_FROM_DEVICE` (or `DMA_BIDIRECTIONAL`) mapping. This leaves `mapped_sg[0]` to be unmapped with `DMA_ATTR_SKIP_CPU_SYNC` without ever being explicitly synced. However, this is structurally correct: for `DMA_TO_DEVICE` mappings, the CPU does not expect data to be written back by the device, and the standard DMA API implementation for unmapping `DMA_TO_DEVICE` does not invalidate the CPU cache or copy back bounce buffers anyway. Skipping it is effectively a no-op.\",\"stage\":\"execution-flow\",\"type\":\"Unsynchronized DMA_TO_DEVICE Buffers\"},{\"description\":\"Possible memory leak of `split_sg` scatterlist in `sa_run()` if `dma_map_sgtable()` fails for the destination buffer.\",\"locations\":[{\"code_snippet\":\"if (ret)\\n\\tgoto err_cleanup;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1228,\"why_this_location_matters\":\"This is where the destination mapping fails and jumps to the cleanup path.\"},{\"code_snippet\":\"kfree(mapped_sg->split_sg);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_sa_rx_data\",\"line\":1033,\"why_this_location_matters\":\"This is the cleanup logic that correctly frees the split scatterlist based on the 'mapped' boolean flag.\"}],\"reasoning\":\"If `dma_map_sgtable()` succeeds for the source buffer (`mapped_sg[0]`), `sg_split()` may allocate a new scatterlist and assign it to `mapped_sg[0].split_sg`. If the subsequent `dma_map_sgtable()` for the destination buffer (`mapped_sg[1]`) fails, the function jumps to `err_cleanup` and calls `sa_free_sa_rx_data()`. This could appear to leak `mapped_sg[0].split_sg` since the destination failed. However, `sa_free_sa_rx_data()` specifically iterates over the `mapped_sg` array and checks the `mapped` boolean flag. Since `mapped_sg[0].mapped` was set to true before the failure, it correctly calls `kfree(mapped_sg->split_sg)` for the source buffer, preventing the leak.\",\"stage\":\"resources\",\"type\":\"Memory Leak\"},{\"description\":\"Possible use-after-free of stack variable `sa_req` in async callback `sa_aes_dma_in_callback`.\",\"locations\":[{\"code_snippet\":\"struct sa_req sa_req = { 0 };\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_run\",\"line\":1303,\"why_this_location_matters\":\"This is the stack allocation of the request wrapper that is passed down.\"},{\"code_snippet\":\"rxd->req = (void *)req->base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1251,\"why_this_location_matters\":\"This is where the long-lived dynamically allocated structure stores a safe reference to the actual crypto request, avoiding reliance on the stack structure.\"}],\"reasoning\":\"In `sa_cipher_run()`, the `sa_req` structure is allocated on the stack and passed by reference to `sa_run(&sa_req)`. Because the DMA operation is asynchronous, there is a risk that the DMA completion callback could access this stack variable after `sa_cipher_run()` returns. However, `sa_run()` synchronously copies all necessary information (like `req->base`, `req->enc`, `req->ctx->iv_idx`) out of `sa_req` into the dynamically allocated `struct sa_rx_data *rxd`, and sets `rxd->req = (void *)req->base;`. The callback uses `rxd` and the original crypto request, completely ignoring the stack-allocated `sa_req`. Thus, no UAF can occur.\",\"stage\":\"resources\",\"type\":\"Use-After-Free\"},{\"description\":\"Skipping CPU cache sync on DMA unmap might leave the buffer or bounce buffer in an inconsistent state during error handling.\",\"locations\":[{\"code_snippet\":\"err_cleanup:\\n\\tsa_free_sa_rx_data(rxd);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1319,\"why_this_location_matters\":\"This is the error path where unmapping occurs without a preceding explicit device-to-CPU sync, testing the safety of unconditionally skipping the CPU sync.\"}],\"reasoning\":\"1. In the error path of `sa_run` (e.g., if DMA mapping or descriptor preparation fails), `sa_free_sa_rx_data()` is called without a preceding call to `sa_sync_from_device()`.\\n2. Because `DMA_ATTR_SKIP_CPU_SYNC` is applied, `dma_unmap_sgtable()` skips cache invalidation and does not copy bounce buffer (SWIOTLB) contents back to the original CPU buffer.\\n3. However, since the DMA operation was never submitted to the hardware on this error path, the device never wrote to the DMA buffer.\\n4. Therefore, the CPU buffer already contains the correct original data, and skipping the bounce buffer copy-back is both safe and desirable as it prevents overwriting the pristine memory with uninitialized/stale bounce buffer contents.\",\"stage\":\"security\",\"type\":\"Data Corruption / Inconsistent State\"},{\"description\":\"Potential integer underflow in `sa_aead_run()` when calculating `enc_size` and `auth_size` for decryption if `req->cryptlen` is smaller than the authentication tag size.\",\"locations\":[{\"code_snippet\":\"\\tif (!enc) {\\n\\t\\tenc_size -= crypto_aead_authsize(tfm);\\n\\t\\tauth_size -= crypto_aead_authsize(tfm);\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aead_run\",\"line\":1895,\"why_this_location_matters\":\"This is where sizes are modified based on the authentication tag length, which would underflow if the total input length wasn't validated.\"}],\"reasoning\":\"1. In `sa_aead_run()`, when handling a decryption request (`!enc`), `crypto_aead_authsize(tfm)` is subtracted from `enc_size` (derived from `req->cryptlen`) and `auth_size`.\\n2. If an attacker could supply a ciphertext shorter than the required authentication tag size, this subtraction would underflow, resulting in massive integer values passed to the DMA engine bounds checks.\\n3. However, this is structurally prevented by the kernel's cryptographic subsystem: the core function `crypto_aead_decrypt()` (in `crypto/aead.c`) explicitly checks that `req->cryptlen >= crypto_aead_authsize(aead)` and returns `-EINVAL` before ever dispatching to the hardware driver's decrypt callback.\\n4. As a result, an underflow condition is mathematically impossible at this layer.\",\"stage\":\"security\",\"type\":\"Integer Underflow\"},{\"description\":\"Skipping CPU sync on dma_unmap_sgtable() via DMA_ATTR_SKIP_CPU_SYNC might skip the final copy from the SWIOTLB bounce buffer to CPU memory, potentially causing data loss.\",\"locations\":[{\"code_snippet\":\"mapped_sg->dir, DMA_ATTR_SKIP_CPU_SYNC);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_sa_rx_data\",\"line\":1062,\"why_this_location_matters\":\"This is where the unmap bypasses cache invalidation and bounce-buffer copybacks.\"},{\"code_snippet\":\"dma_sync_sgtable_for_cpu(rxd->ddev, sgt, DMA_FROM_DEVICE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1050,\"why_this_location_matters\":\"This manual sync proves that the required bounce-buffer copyback to the CPU already occurred before the unmap.\"}],\"reasoning\":\"1. `sa_sync_from_device()` is explicitly called in the DMA completion callbacks prior to any CPU buffer modifications.\\n2. `sa_sync_from_device()` executes `dma_sync_sgtable_for_cpu(..., DMA_FROM_DEVICE)`.\\n3. On systems using SWIOTLB, this sync performs the necessary `swiotlb_bounce()` operation, effectively copying the device-written data from the bounce buffer to the CPU memory.\\n4. CPU operations (such as `scatterwalk_map_and_copy`) then legitimately modify the CPU memory.\\n5. If `dma_unmap_sgtable()` subsequently executed without `SKIP_CPU_SYNC`, it would trigger another redundant bounce buffer copy-back, overwriting the CPU's recent modifications with stale bounce buffer data. Therefore, the addition of `DMA_ATTR_SKIP_CPU_SYNC` safely preserves the CPU modifications without losing device data.\",\"stage\":\"hardware\",\"type\":\"Data Loss / DMA Bounce Buffers\"},{\"description\":\"In out-of-place crypto operations (`diff_dst == true`), `sa_sync_from_device()` only synchronizes `mapped_sg[1]` (destination). `mapped_sg[0]` (source) is unmapped with `DMA_ATTR_SKIP_CPU_SYNC` without ever being explicitly synced for the CPU.\",\"locations\":[{\"code_snippet\":\"dir_src = DMA_TO_DEVICE;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1152,\"why_this_location_matters\":\"This establishes that the source buffer is treated as read-only by the hardware.\"},{\"code_snippet\":\"else\\n\\tsgt = &rxd->mapped_sg[1].sgt;\\n\\ndma_sync_sgtable_for_cpu(rxd->ddev, sgt, DMA_FROM_DEVICE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1047,\"why_this_location_matters\":\"This shows the source buffer is skipped during explicit CPU synchronization, which is correctly offset by its DMA_TO_DEVICE mapping direction.\"}],\"reasoning\":\"1. When `diff_dst == true`, the source buffer `mapped_sg[0]` is strictly mapped with the `DMA_TO_DEVICE` direction.\\n2. A `DMA_TO_DEVICE` mapping indicates the hardware will solely read from the buffer and will not write to it.\\n3. Since there are no hardware writes to propagate back to CPU memory, a CPU cache invalidation or SWIOTLB bounce-back is entirely unnecessary.\\n4. Therefore, unconditionally skipping CPU sync on unmap via `DMA_ATTR_SKIP_CPU_SYNC` for the source buffer is safe and conforms to DMA API semantics.\",\"stage\":\"hardware\",\"type\":\"Missing CPU Synchronization\"}],\"dismissed_concerns_count\":11,\"findings\":[]}","patch_id":189886,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2239477,"tokens_in":3089635,"tokens_out":12142},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466859,"id":167782,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"dma_sync_sgtable_for_device() is called with a hardcoded DMA_TO_DEVICE direction in sa_run(), which mismatches the mapping direction when the buffer is mapped as DMA_BIDIRECTIONAL (in-place crypto operations).\",\"locations\":[{\"code_snippet\":\"\\tdma_sync_sgtable_for_device(ddev, &mapped_sg->sgt, DMA_TO_DEVICE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1228,\"why_this_location_matters\":\"This is where the manual DMA sync for the device hardcodes DMA_TO_DEVICE, violating the API if mapped_sg was mapped as DMA_BIDIRECTIONAL.\"}],\"patch_index\":26,\"patch_subject\":\"[PATCH 26/30] crypto: sa2ul - use correct DMA direction in sa_sync_from_device\",\"preexisting\":true,\"reasoning\":\"The commit fixes a DMA-API mapping violation for `dma_sync_sgtable_for_cpu()` in `sa_sync_from_device()` by correctly using the dynamically stored direction, but completely missed the identical error on the TX side in `sa_run()`. In `sa_run()`, if `req->src == req->dst` (in-place operation), the buffer is mapped with `DMA_BIDIRECTIONAL`. Immediately after mapping, `dma_sync_sgtable_for_device()` is called with a hardcoded `DMA_TO_DEVICE` direction. The DMA API strictly mandates that the direction argument passed to sync functions must exactly match the direction used during mapping. Passing `DMA_TO_DEVICE` when the buffer was mapped as `DMA_BIDIRECTIONAL` violates this constraint and triggers a 'device driver syncs DMA memory with different direction' warning if `CONFIG_DMA_API_DEBUG` is enabled.\",\"type\":\"DMA API Violation (Incomplete Fix)\"}],\"concerns_count\":4,\"dismissed_concerns\":[{\"description\":\"Potential unaligned access or incorrect byte ordering when reading `req->iv` via `u32 *enc_iv` pointer casting.\",\"locations\":[{\"code_snippet\":\"\\t\\t\\tu32 *enc_iv = (u32 *)req->enc_iv;\\n\\n\\t\\t\\tfor (j = 0; i < upd_info->enc_iv.size; i += 4, j++) {\\n\\t\\t\\t\\tdata[j] = cpu_to_be32(*enc_iv);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":689,\"why_this_location_matters\":\"This is where the IV bytes are interpreted as 32-bit integers, sparking the initial endianness and alignment concerns.\"}],\"reasoning\":\"In `sa_update_cmdl`, the byte array `req->enc_iv` is cast to a `u32 *` and dereferenced. On architectures with strict alignment requirements, this could theoretically cause an unaligned access fault. Furthermore, `cpu_to_be32()` swaps the bytes of each 32-bit chunk on little-endian architectures. However, upon deeper inspection, the crypto API guarantees that `req->iv` is aligned to `CRYPTO_MINALIGN`, safely satisfying the 32-bit alignment requirement. Regarding byte ordering, the callback `sa_aes_dma_in_callback()` reads the IV back from the device metadata and performs the exact inverse operation (`be32_to_cpu`), ensuring the transformation is fully symmetrical.\",\"type\":\"Data Corruption / Unaligned Access\"},{\"description\":\"Possible uninitialized access to `mapped_sg[1]` or use-after-free in `sa_sync_from_device` if destination mapping fails during `sa_run`.\",\"locations\":[{\"code_snippet\":\"dir = rxd->mapped_sg[1].dir;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1051,\"why_this_location_matters\":\"This accesses the DMA direction that could theoretically be uninitialized if the setup failed.\"},{\"code_snippet\":\"if (req->src != req->dst) { diff_dst = true; dir_src = DMA_TO_DEVICE; } else { diff_dst = false; dir_src = DMA_BIDIRECTIONAL; }\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1146,\"why_this_location_matters\":\"Proves that mapped_sg[0].dir is deterministically initialized to either DMA_TO_DEVICE or DMA_BIDIRECTIONAL, keeping execution safe.\"},{\"code_snippet\":\"err_cleanup:\\n\\tsa_free_sa_rx_data(rxd);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":1322,\"why_this_location_matters\":\"Proves that failed mapping paths bypass syncing entirely and cleanly release resources without memory leaks.\"}],\"reasoning\":\"If `dma_map_sgtable` fails for `mapped_sg[1]` (when `diff_dst == true`), it could theoretically leave `mapped_sg[1].dir` uninitialized. However, `sa_sync_from_device` is only invoked by DMA completion callbacks, which strictly run after successful submission to the hardware. If mapping fails, `sa_run` jumps to `err_cleanup`, gracefully unmaps any initialized tables, frees resources via `sa_free_sa_rx_data`, and returns synchronously. The DMA transaction is never submitted, meaning the callback is never executed. Furthermore, the `sa_rx_data` struct is allocated with `kzalloc`, ensuring all fields default to zero safely.\",\"type\":\"Uninitialized Memory Access / Logic Error\"},{\"description\":\"Missing CPU cache sync for the source buffer (mapped_sg[0]) when diff_dst == true.\",\"locations\":[{\"code_snippet\":\"} else {\\n\\t\\tsgt = &rxd->mapped_sg[1].sgt;\\n\\t\\tdir = rxd->mapped_sg[1].dir;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1049,\"why_this_location_matters\":\"This path explicitly syncs only the destination scatterlist when source and destination are separate buffers, appropriately skipping the source.\"}],\"reasoning\":\"When diff_dst == true, mapped_sg[0] is mapped as DMA_TO_DEVICE. The sa_sync_from_device function correctly avoids syncing it, relying on the 'else' branch to sync mapped_sg[1] (the destination buffer, mapped as DMA_FROM_DEVICE). This is entirely safe because DMA_TO_DEVICE buffers only pass data to the device; the device never modifies them. Therefore, the CPU's cache remains authoritative and no invalidation is needed after the DMA transaction completes.\",\"type\":\"Resource Management\"},{\"description\":\"sa_sync_from_device() could still pass the wrong direction for out-of-place decryption.\",\"locations\":[{\"code_snippet\":\"dir = rxd->mapped_sg[1].dir;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sync_from_device\",\"line\":1051,\"why_this_location_matters\":\"This confirms the correct mapping direction is dynamically retrieved for the destination buffer in the out-of-place fallback path.\"}],\"reasoning\":\"Investigation of `sa_run()` shows that for out-of-place operations (`diff_dst == true`), `mapped_sg[1]` is explicitly mapped with `DMA_FROM_DEVICE`. The new patch correctly checks if `mapped_sg[0].dir == DMA_BIDIRECTIONAL`; if not, it uses `mapped_sg[1].dir` which is exactly `DMA_FROM_DEVICE`. This guarantees the CPU sync direction always perfectly matches the mapped direction, completely resolving the original bug on the CPU side.\",\"type\":\"DMA Direction Sync\"}],\"dismissed_concerns_count\":4,\"findings\":[]}","patch_id":189892,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":3985342,"tokens_in":4921672,"tokens_out":18186},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466872,"id":167783,"inline_review":"commit c6d5bbb3152ab4bc1385b08c8ea64f22939c5829\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - change dma_alloc_pool to mempool\n\nThis commit replaces dma_pool_alloc() with a kmalloc-backed mempool for\nallocating the SA2UL security context. Because the memory is no longer\nguaranteed to be coherent, it adds explicit dma_map_single() and\ndma_unmap_single() calls around device operations.\n\n> diff --git a/drivers/crypto/sa2ul.c b/drivers/crypto/sa2ul.c\n> index df905b3913398..cadc8db14bbbf 100644\n> --- a/drivers/crypto/sa2ul.c\n> +++ b/drivers/crypto/sa2ul.c\n[ ... ]\n> @@ -802,6 +806,12 @@ int sa_init_sc(struct sa_ctx_info *ctx, const struct sa_match_data *match_data,\n>  \t/* swizzle the security context */\n>  \tsa_swiz_128(sc_buf, SA_CTX_MAX_SZ);\n>  \n> +\tctx->sc_phys = dma_map_single(dev, ctx->sc, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\n\n[Severity: High]\nCould this unconditionally mapping leak previous DMA mappings?\n\nIf setkey() is called multiple times on the same transform (e.g., during key\nrotation), sa_init_sc() will unconditionally call dma_map_single() and\noverwrite ctx->sc_phys. Since dma_unmap_single() is not called to release\nthe previous mapping before re-mapping, does this permanently leak the old\nmapping?\n\n[Severity: Medium]\nWhen setkey() is invoked multiple times, sa_init_sc() modifies ctx->sc\ndirectly (e.g., calling memzero_explicit() earlier in the function) before\nmapping it again. If the buffer is already mapped for bidirectional DMA from\na previous setkey() call, does modifying this memory without first unmapping\nit or syncing it violate DMA API semantics?\n\n> +\tif (dma_mapping_error(dev, ctx->sc_phys)) {\n> +\t\tmempool_free(ctx->sc, data->sc_pool);\n> +\t\treturn -ENOMEM;\n> +\t}\n\n[Severity: High]\nDoes this leave a dangling pointer in the context structure?\n\nIf dma_map_single() fails, mempool_free() is called to release the security\ncontext, but ctx->sc is not set to NULL.\n\nIf the user later cleans up the transform, sa_free_ctx_info() will be called:\n\nsa_free_ctx_info()\n    if (ctx->sc) {\n        memzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\n        dma_unmap_single(dev, ctx->sc_phys, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\n        mempool_free(ctx->sc, data->sc_pool);\n    }\n\nSince ctx->sc is still non-NULL, wouldn't this result in a use-after-free\nwrite during memzero_explicit() and a double-free during mempool_free()?\n\n[ ... ]\n> @@ -824,7 +835,8 @@ static void sa_free_ctx_info(struct sa_ctx_info *ctx,\n>  \n>  \tif (ctx->sc) {\n>  \t\tmemzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\n> -\t\tdma_pool_free(data->sc_pool, ctx->sc, ctx->sc_phys);\n> +\t\tdma_unmap_single(dev, ctx->sc_phys, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\n\n[Severity: High]\nCould this ordering leak sensitive cryptographic keys?\n\nThe zeroing via memzero_explicit() happens before the DMA unmap. If a bounce\nbuffer (like SWIOTLB) is used, won't the subsequent dma_unmap_single()\nsynchronize the device's view by copying the bounce buffer contents back to\nhost memory, overwriting the freshly zeroed buffer with plaintext keys?\n\n[Severity: High]\nCan this attempt to unmap an uninitialized physical address of 0?\n\nIn sa_init_ctx_info(), the memory for ctx->sc is allocated, but its DMA\nmapping is deferred to sa_init_sc(), leaving ctx->sc_phys at 0.\n\nIf a transform is allocated but destroyed without setkey() ever being called,\nor if cra_init fails, sa_free_ctx_info() is invoked. Since ctx->sc is\nnon-NULL, it will unconditionally call dma_unmap_single() on ctx->sc_phys.\nCould this cause IOMMU faults or corruption of DMA tracking structures?\n\n> +\t\tmempool_free(ctx->sc, data->sc_pool);\n>  \t\tctx->sc = NULL;\n>  \t}\n>  }\n[ ... ]\n> @@ -843,7 +855,7 @@ static int sa_init_ctx_info(struct sa_ctx_info *ctx,\n>  \n>  \tctx->sc_id = (u16)bn;\n>  \n> -\tctx->sc = dma_pool_alloc(data->sc_pool, GFP_KERNEL, &ctx->sc_phys);\n> +\tctx->sc = mempool_alloc(data->sc_pool, GFP_KERNEL);\n>  \tif (!ctx->sc) {\n>  \t\tdev_err(&data->pdev->dev, \"Failed to allocate SC memory\\n\");\n>  \t\terr = -ENOMEM;\n\n[Severity: Low]\nIs this error handling dead code?\n\nAccording to MM subsystem guidelines, mempool_alloc() retries indefinitely\nwhen __GFP_DIRECT_RECLAIM is set (which is included in GFP_KERNEL). Because\nthe allocation will block until successful, will ctx->sc ever be NULL here?","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"Ignored return value in SHA initialization leads to NULL pointer dereference.\",\"locations\":[{\"code_snippet\":\"\\tsa_sha_cra_init_alg(tfm, \\\"sha1\\\");\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1633,\"why_this_location_matters\":\"The error code is silently dropped here instead of aborting initialization.\"},{\"code_snippet\":\"\\tmemzero_explicit(sc_buf, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":755,\"why_this_location_matters\":\"The NULL pointer (sc_buf = ctx->sc) is dereferenced here.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":true,\"reasoning\":\"1. In `sa_sha1_cra_init()` (and related algorithms), the return value of `sa_sha_cra_init_alg(tfm, \\\"sha1\\\")` is silently ignored.\\n2. If `sa_sha_cra_init_alg` fails (e.g., if `sa_init_ctx_info()` were to return `-ENOMEM`), `ctx->enc.sc` is left as NULL.\\n3. Execution continues blindly to `sa_sha_setup()`, which calls `sa_init_sc(&ctx->enc, ...)`.\\n4. `sa_init_sc()` immediately dereferences `ctx->sc` by passing it to `memzero_explicit(ctx->sc, ...)`, causing a deterministic kernel panic.\",\"type\":\"NULL Pointer Dereference\"}],\"concerns_count\":30,\"dismissed_concerns\":[{\"description\":\"Suspicious parameter `min_nr = 64` passed to `mempool_create_kmalloc_pool()` drops explicit alignment.\",\"locations\":[{\"code_snippet\":\"\\tdev_data->sc_pool = mempool_create_kmalloc_pool(64, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_mem\",\"line\":2259,\"why_this_location_matters\":\"This shows the conceptually incorrect but practically harmless usage of 64 for min_nr instead of alignment.\"}],\"reasoning\":\"When porting from `dma_pool_create` to `mempool_create_kmalloc_pool`, the developer incorrectly mapped the alignment parameter (`64`) of the old API to the `min_nr` parameter of the new API. While this is a conceptual copy-paste error that needlessly preallocates 64 elements (16 KB) as an OOM reserve, it is mathematically valid and doesn't constitute a functional bug. The original hardware 64-byte alignment requirement is coincidentally satisfied because the context size is 256 bytes (`SA_CTX_MAX_SZ`), and `kmalloc(256)` returns 256-byte aligned memory naturally.\",\"type\":\"Suspicious API Usage\"},{\"description\":\"Incorrect context ID release in `sa_free_ctx_info()` missing the `- data->sc_id_start` calculation.\",\"locations\":[{\"code_snippet\":\"\\tbn = ctx->sc_id;\\n\\tspin_lock(&data->scid_lock);\\n\\t__clear_bit(bn, data->ctx_bm);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":830,\"why_this_location_matters\":\"This demonstrates the new method of deriving the bit index directly from `sc_id`.\"}],\"reasoning\":\"In the baseline code, the bitmask was manipulated using `bn = ctx->sc_id - data->sc_id_start`. The patch removes `sc_id_start` and simply uses the bit number directly during assignment in `sa_init_ctx_info()` (`ctx->sc_id = (u16)bn;`). Thus, `bn = ctx->sc_id;` correctly identifies the bit in `sa_free_ctx_info()`, proving the simplification is mathematically sound.\",\"type\":\"Logic Error\"},{\"description\":\"Potential sleep in atomic context during mempool allocation in `sa_init_ctx_info()`.\",\"locations\":[{\"code_snippet\":\"\\tspin_unlock(&data->scid_lock);\\n\\n\\tctx->sc_id = (u16)bn;\\n\\n\\tctx->sc = mempool_alloc(data->sc_pool, GFP_KERNEL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":854,\"why_this_location_matters\":\"This demonstrates that the lock is released prior to the `GFP_KERNEL` allocation.\"}],\"reasoning\":\"The function `sa_init_ctx_info()` acquires the `data->scid_lock` spinlock to safely assign a context ID. It subsequently calls `mempool_alloc()` with `GFP_KERNEL`, which can sleep. However, `spin_unlock(&data->scid_lock)` is explicitly called immediately *before* the `mempool_alloc()` call, ensuring no spinlock is held during the potentially sleeping allocation.\",\"type\":\"Sleeping in Atomic Context\"},{\"description\":\"`sa_dump_sc` accesses a DMA-mapped buffer from the CPU side without synchronization.\",\"locations\":[{\"code_snippet\":\"\\tsa_dump_sc(sc_buf, ctx->sc_phys);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":818,\"why_this_location_matters\":\"This debug function reads the buffer right after it has been mapped for DMA.\"}],\"reasoning\":\"`sa_init_sc` maps the buffer with `dma_map_single(..., DMA_BIDIRECTIONAL)`. Immediately after, `sa_dump_sc()` reads the buffer. Reading memory while it is mapped for DMA by the device without `dma_sync_single_for_cpu()` is formally a DMA API violation. However, this is wrapped in an `#ifdef DEBUG` block, the CPU just finished writing to this buffer before mapping it so the cache lines are up-to-date, and the hardware hasn't actually been triggered to run yet. Thus, it's not a practical bug.\",\"type\":\"DMA API Violation\"}],\"dismissed_concerns_count\":4,\"findings\":[{\"locations\":[{\"code_snippet\":\"\\tif (dma_mapping_error(dev, ctx->sc_phys)) {\\n\\t\\tmempool_free(ctx->sc, data->sc_pool);\\n\\t\\treturn -ENOMEM;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":810,\"why_this_location_matters\":\"The error path frees the memory but leaves a dangling pointer in the TFM context structure.\"},{\"code_snippet\":\"\\tif (ctx->sc) {\\n\\t\\tmemzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\\n\\t\\tdma_unmap_single(dev, ctx->sc_phys, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\\n\\t\\tmempool_free(ctx->sc, data->sc_pool);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":837,\"why_this_location_matters\":\"The cleanup function unconditionally uses the dangling pointer, triggering a UAF write (memzero) and double-free.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: Use-After-Free and Double-Free on DMA mapping failure\",\"severity\":\"High\",\"severity_explanation\":\"1. Consequence: Memory corruption (Use-After-Free write and Double-Free), leading to crashes or exploitable memory states.\\n2. Triggering path: If `dma_map_single()` fails in `sa_init_sc()` during a `setkey()` operation, `mempool_free()` is called to release the security context (`ctx->sc`), but the pointer `ctx->sc` is not set to `NULL`. The function returns `-ENOMEM`.\\n3. Reachability: When the user handles the `setkey()` failure by tearing down the transform (or when it cleans up later), `sa_free_ctx_info()` is called. It checks `if (ctx->sc)`, which is true due to the dangling pointer. It then calls `memzero_explicit()` (UAF write), `dma_unmap_single()` (using the error code as the DMA address), and `mempool_free()` again (Double-Free).\"},{\"locations\":[{\"code_snippet\":\"\\t\\tmemzero_explicit(ctx->sc, SA_CTX_MAX_SZ);\\n\\t\\tdma_unmap_single(dev, ctx->sc_phys, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":837,\"why_this_location_matters\":\"The zeroing happens before the DMA unmap, causing the CPU writes to be discarded or overwritten by bounce buffer synchronization.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: Cryptographic key leak due to incorrect DMA unmap ordering\",\"severity\":\"High\",\"severity_explanation\":\"1. Consequence: Sensitive cryptographic keys are left in plaintext in physical memory instead of being wiped.\\n2. Triggering path: During TFM teardown, `sa_free_ctx_info()` zeroizes the security context via `memzero_explicit()` on the CPU, and then subsequently unmaps it via `dma_unmap_single(..., DMA_BIDIRECTIONAL)`.\\n3. Reachability: If a bounce buffer (like SWIOTLB) is used, the unmap operation synchronizes the device's view by copying the bounce buffer contents back to host memory, overwriting the freshly zeroed buffer with the plaintext keys. Even without bounce buffers, unmapping after zeroing on non-coherent architectures can drop the CPU zeroes via cache invalidation. The correct DMA API order requires unmapping or syncing the buffer before CPU zeroization.\"},{\"locations\":[{\"code_snippet\":\"\\tctx->sc = mempool_alloc(data->sc_pool, GFP_KERNEL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":855,\"why_this_location_matters\":\"The memory is allocated here but the DMA mapping is deferred, leaving ctx->sc_phys at 0.\"},{\"code_snippet\":\"\\t\\tdma_unmap_single(dev, ctx->sc_phys, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_free_ctx_info\",\"line\":838,\"why_this_location_matters\":\"The uninitialized/zero DMA address is unconditionally unmapped here if setkey was bypassed.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: Invalid DMA unmap of physical address 0\",\"severity\":\"High\",\"severity_explanation\":\"1. Consequence: IOMMU faults, system crashes, or corruption of DMA tracking structures.\\n2. Triggering path: In `sa_init_ctx_info()`, the memory for `ctx->sc` is allocated, but its DMA mapping is deferred to `sa_init_sc()`, leaving `ctx->sc_phys` at 0. If a transform is allocated but destroyed without `setkey()` ever being called, or if `cra_init` fails (e.g., fallback transform allocation failure), `sa_free_ctx_info()` is invoked.\\n3. Reachability: `sa_free_ctx_info()` sees `ctx->sc` is non-NULL and unconditionally calls `dma_unmap_single(..., ctx->sc_phys, ...)`, attempting to unmap the uninitialized address 0.\"},{\"locations\":[{\"code_snippet\":\"\\tctx->sc_phys = dma_map_single(dev, ctx->sc, SA_CTX_MAX_SZ, DMA_BIDIRECTIONAL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":809,\"why_this_location_matters\":\"A new DMA mapping is established unconditionally, leaking any prior mapping.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: DMA mapping leak on sequential setkey calls\",\"severity\":\"High\",\"severity_explanation\":\"1. Consequence: Resource leak (IOMMU space / SWIOTLB slots exhaustion), potentially leading to Denial of Service.\\n2. Triggering path: The Crypto API permits multiple calls to `setkey()` on the same transform (e.g., key rotation). Each call triggers `sa_init_sc()`, which unconditionally maps the buffer via `dma_map_single()` and overwrites `ctx->sc_phys`.\\n3. Reachability: Readily reachable. Because `dma_unmap_single()` is never called to release the previous mapping before re-mapping, the old DMA mapping is permanently leaked.\"},{\"locations\":[{\"code_snippet\":\"\\tmemzero_explicit(sc_buf, SA_CTX_MAX_SZ);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_sc\",\"line\":755,\"why_this_location_matters\":\"The CPU modifies the buffer here, which is illegal if it is already DMA-mapped from a previous setkey call.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: CPU modification of mapped DMA memory without synchronization\",\"severity\":\"Medium\",\"severity_explanation\":\"1. Consequence: DMA API violation resulting in cache coherency corruption and unpredictable device states on non-coherent architectures.\\n2. Triggering path: When `setkey()` is invoked multiple times on the same transform, `sa_init_sc()` modifies `ctx->sc` directly via `memzero_explicit()` and further context setup.\\n3. Reachability: The buffer is already mapped for bidirectional DMA from the previous `setkey()` call. Modifying memory while it is owned by the device without first unmapping it or calling `dma_sync_single_for_cpu()` violates strict DMA API semantics.\"},{\"locations\":[{\"code_snippet\":\"\\tif (!ctx->sc) {\\n\\t\\tdev_err(&data->pdev->dev, \\\"Failed to allocate SC memory\\\\n\\\");\\n\\t\\terr = -ENOMEM;\\n\\t\\tgoto scid_rollback;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_init_ctx_info\",\"line\":859,\"why_this_location_matters\":\"The error path can never be taken because mempool_alloc with GFP_KERNEL blocks forever until memory is available.\"}],\"patch_index\":27,\"patch_subject\":\"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool\",\"preexisting\":false,\"problem\":\"mm: sa2ul: Dead code error path due to GFP_KERNEL mempool allocation\",\"severity\":\"Low\",\"severity_explanation\":\"1. Consequence: Unnecessary code complexity and misleading error handling.\\n2. Triggering path: `sa_init_ctx_info()` allocates memory using `mempool_alloc(data->sc_pool, GFP_KERNEL)`. According to MM subsystem guidelines, `mempool_alloc()` retries indefinitely when `__GFP_DIRECT_RECLAIM` is set (included in `GFP_KERNEL`).\\n3. Reachability: Because the allocation can never fail and will block until successful, it will never return `NULL`. The subsequent `if (!ctx->sc)` check and its associated error rollback logic are completely dead code.\"}]}","patch_id":189889,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":2137575,"tokens_in":2796556,"tokens_out":30381},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466896,"id":167784,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The initialization functions sa_sha1_cra_init, sa_sha256_cra_init, and sa_sha512_cra_init ignore the return values of sa_sha_cra_init_alg and sa_sha_setup.\",\"locations\":[{\"code_snippet\":\"sa_sha_cra_init_alg(tfm, \\\"sha1\\\");\\n\\n\\tad.hash_size = SHA1_DIGEST_SIZE;\\n\\tad.auth_ctrl = SA_AUTH_SW_CTRL_SHA1;\\n\\n\\tsa_sha_setup(ctx, &ad);\\n\\n\\treturn 0;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha1_cra_init\",\"line\":1583,\"why_this_location_matters\":\"The error codes from both initialization functions are discarded, masking failures from the caller.\"}],\"patch_index\":28,\"patch_subject\":\"[PATCH 28/30] crypto: sa2ul - route requests through crypto_engine\",\"preexisting\":true,\"reasoning\":\"`sa_sha_cra_init_alg` and `sa_sha_setup` both return integer error codes (e.g., `-EINVAL`, `-ENOMEM`). In `sa_sha1_cra_init` (and the other hash initializers), these functions are called without checking or propagating their return values. If they fail to allocate memory or initialize the context, the function silently returns `0`, tricking the crypto framework into believing the algorithm was initialized successfully. Later operations using this uninitialized or partially initialized context will likely lead to NULL pointer dereferences or memory corruption.\",\"type\":\"Unchecked Return Value\"}],\"concerns_count\":5,\"dismissed_concerns\":[{\"description\":\"The DMA completion callbacks fetch the hardware context `pdata` via the global variable `sa_k3_dev`, risking cross-device corruption.\",\"locations\":[{\"code_snippet\":\"\\tstruct sa_crypto_data *pdata = dev_get_drvdata(sa_k3_dev);\\n...\\n\\tcrypto_finalize_skcipher_request(pdata->engine, req, 0);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_dma_in_callback\",\"line\":1090,\"why_this_location_matters\":\"This is where the global instance is used to finalize the request.\"}],\"reasoning\":\"While fetching `pdata` from a global variable is generally risky, this driver implements a strict singleton architecture (a single statically allocated `sa_algs` array registered by name). The crypto subsystem prevents probing a second instance due to name collisions. Therefore, retrieving `pdata` via the global `sa_k3_dev` is a benign artifact of this singleton design and cannot trigger a cross-instance race condition in practice.\",\"type\":\"Global State / Concurrency\"},{\"description\":\"Potential kthread memory leak if `crypto_engine_start()` fails.\",\"locations\":[{\"code_snippet\":\"ret = crypto_engine_start(dev_data->engine);\\n\\tif (ret)\\n\\t\\tgoto free_engine;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2507,\"why_this_location_matters\":\"This is the error path that safely tears down the newly allocated engine.\"}],\"reasoning\":\"If `crypto_engine_start()` fails, it branches to `free_engine:` and calls `crypto_engine_exit()`. The concern is that `crypto_engine_exit()` could return `-EBUSY` and skip destroying the kworker. However, `crypto_engine_start()` on a freshly allocated engine will never fail because `engine->running` and `engine->busy` are always initialized to false by `crypto_engine_alloc_init()`. The engine memory is also safely managed by devres. No leak occurs.\",\"type\":\"Memory Leak\"},{\"description\":\"Potential memory corruption, misalignment, or insufficient space allocated when embedding `fallback_req` in the request context.\",\"locations\":[{\"code_snippet\":\"struct sa_cipher_req_ctx {\\n\\tbool enc;\\n\\tstruct skcipher_request fallback_req;\\n};\",\"file\":\"drivers/crypto/sa2ul.h\",\"function_or_symbol\":\"sa_cipher_req_ctx\",\"line\":271,\"why_this_location_matters\":\"This establishes the struct whose layout is securely padded by the compiler.\"},{\"code_snippet\":\"crypto_skcipher_set_reqsize(tfm, sizeof(struct sa_cipher_req_ctx) +\\n\\t\\t\\t\\t\\t crypto_skcipher_reqsize(child));\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_cra_init\",\"line\":918,\"why_this_location_matters\":\"This handles sizing the request context so it securely accommodates the subrequest.\"}],\"reasoning\":\"The `reqsize` is correctly updated to `sizeof(struct sa_cipher_req_ctx) + crypto_skcipher_reqsize(child)`. Because `fallback_req` is placed at the end of the context structure and its trailing flexible array `__ctx` has the `CRYPTO_MINALIGN_ATTR` attribute, the compiler properly aligns it. The extra child context space accurately begins at the end of `fallback_req`. This layout safely conforms to the crypto API memory bounds without misalignment or corruption.\",\"type\":\"Memory Layout\"},{\"description\":\"Fallback paths and 0-length payloads bypass the crypto_engine queue.\",\"locations\":[{\"code_snippet\":\"if (req->cryptlen > SA_MAX_DATA_SZ || ...\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_run\",\"line\":1362,\"why_this_location_matters\":\"Fallback check executed before request transfer to the engine queue.\"},{\"code_snippet\":\"if (!auth_len)\\n\\t\\treturn zero_message_process(req);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_run\",\"line\":1475,\"why_this_location_matters\":\"0-length payloads are processed synchronously without queuing.\"}],\"reasoning\":\"0-length payloads and software fallbacks are handled immediately (synchronously or by directly executing the asynchronous software fallback), bypassing `crypto_transfer_*_request_to_engine`. This is completely safe and permitted by the Linux crypto API, which allows asynchronous algorithms to complete requests synchronously if possible. Software fallbacks do not use the accelerator hardware and thus do not require serialization in the engine queue.\",\"type\":\"API Contract\"},{\"description\":\"Risk of stalled hardware queues or memory leaks if `sa_run_one` fails in `do_one_request`.\",\"locations\":[{\"code_snippet\":\"return sa_run_one(&sa_req);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_do_one_req\",\"line\":1399,\"why_this_location_matters\":\"Returns potentially negative error codes directly to the crypto_engine framework.\"}],\"reasoning\":\"If `sa_run` fails (e.g., due to DMA mapping errors), the dynamically allocated `rxd` structure is safely freed before returning the negative error code. Returning a negative code to the `crypto_engine` is the correct API contract; the engine framework natively intercepts this, completes the active request natively via `crypto_request_complete`, and skips waiting for the hardware callback. The driver flawlessly fulfills its memory management and state machine requirements.\",\"type\":\"Resource Management\"},{\"description\":\"Missing `.update`, `.final`, and `.finup` engine implementations for ahash algorithms.\",\"locations\":[{\"code_snippet\":\".update\\t\\t\\t= sa_sha_update,\\n\\t\\t\\t\\t.final\\t\\t\\t= sa_sha_final,\\n\\t\\t\\t\\t.finup\\t\\t\\t= sa_sha_finup,\\n\\t\\t\\t\\t.digest\\t\\t\\t= sa_sha_run,\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_algs\",\"line\":2053,\"why_this_location_matters\":\"Registers synchronous partial updates alongside a hardware-queued `.digest`.\"}],\"reasoning\":\"The hardware accelerator strictly supports full-packet hashing. Operations requiring partial state (updates) properly delegate to the software fallback synchronously, rather than dispatching into the hardware queue. Therefore, it is correct that only the `.digest` callback delegates to the `crypto_engine` via `.op.do_one_request`.\",\"type\":\"API Contract\"},{\"description\":\"Passing the original request's completion callback directly to the fallback subrequest.\",\"locations\":[{\"code_snippet\":\"skcipher_request_set_callback(subreq, req->base.flags,\\n\\t\\t\\t\\t\\t      req->base.complete,\\n\\t\\t\\t\\t\\t      req->base.data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_run\",\"line\":1373,\"why_this_location_matters\":\"This is where the original completion callback is forwarded to the fallback subrequest.\"}],\"reasoning\":\"The kernel crypto API specifically allows passing `req->base.complete` and `req->base.data` directly to a delegated subrequest (a standard pattern in generic wrappers like `ctr.c` and `gcm.c`). Callers rely on the provided `data` context and do not strict-cast the request object back to original structures assuming it hasn't been wrapped. This preexisting behavior is entirely safe.\",\"type\":\"API Usage\"},{\"description\":\"Possible dangling stack pointer usage when passing stack-allocated `sa_req` down to DMA callback contexts.\",\"locations\":[{\"code_snippet\":\"struct sa_req sa_req = { 0 };\\n...\\nreturn sa_run_one(&sa_req);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_cipher_do_one_req\",\"line\":1388,\"why_this_location_matters\":\"This initiates the sequence where a stack variable is used for synchronous submission data.\"}],\"reasoning\":\"The struct `sa_req` is strictly consumed synchronously. `sa_run` extracts scalar fields from it, prepares the `rxd` structure and DMA descriptors, and submits them to the DMA engine. The pointer that `sa_run` assigns to the asynchronous DMA context (`rxd->req = (void *)req->base;`) strictly points to the heap-allocated original base request, entirely discarding the stack pointer before returning.\",\"type\":\"Dangling Pointer\"},{\"description\":\"Missing completion callback for software fallback in `sa_sha_run`.\",\"locations\":[{\"code_snippet\":\"ahash_request_set_callback(subreq, req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_sha_run\",\"line\":1484,\"why_this_location_matters\":\"This is where the callback is deliberately set to NULL for the fallback.\"}],\"reasoning\":\"The fallback ahash tfm is allocated in `sa_sha_cra_init_alg()` using `crypto_alloc_ahash(alg_base, 0, CRYPTO_ALG_ASYNC)`. Passing `CRYPTO_ALG_ASYNC` as the mask ensures the allocated fallback algorithm must NOT be asynchronous. Therefore, `crypto_ahash_digest()` completes completely synchronously, making an asynchronous completion callback unnecessary. Passing NULL is safe.\",\"type\":\"API Usage\"}],\"dismissed_concerns_count\":9,\"findings\":[]}","patch_id":189895,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":8122320,"tokens_in":10474199,"tokens_out":23560},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466898,"id":167785,"inline_review":"No issues found.","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[{\"description\":\"The driver uses static and global variables for per-device state (`saul_base` and `sa_k3_dev`), causing race conditions, broken encapsulation, and state corruption if multiple instances of the device are probed.\",\"locations\":[{\"code_snippet\":\"static struct device *sa_k3_dev;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":null,\"line\":98,\"why_this_location_matters\":\"File-level global variable used to store device pointer.\"},{\"code_snippet\":\"static void __iomem *saul_base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2466,\"why_this_location_matters\":\"Static local variable used to store device-specific I/O memory base, introducing shared state across lifecycles.\"},{\"code_snippet\":\"sa_k3_dev = dev;\\n\\tdev_data->dev = dev;\\n\\tdev_data->pdev = pdev;\\n\\tplatform_set_drvdata(pdev, dev_data);\\n\\tdev_set_drvdata(sa_k3_dev, dev_data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2484,\"why_this_location_matters\":\"The shared global state is overwritten on each probe without protection, clobbering state from previous instances.\"}],\"patch_index\":29,\"patch_subject\":\"[PATCH 29/30] crypto: sa2ul - report SA engine hardware revision\",\"preexisting\":true,\"reasoning\":\"1. The driver declares a static local variable `static void __iomem *saul_base;` inside `sa_ul_probe()` and a file-level `static struct device *sa_k3_dev;`.\\n2. When `sa_ul_probe()` executes, it unconditionally overwrites both of these with the current device's I/O mapping and device pointer.\\n3. If multiple SA2UL devices are present, unbound/rebound, or hotplugged, subsequent probes will overwrite the global and static state, leading to dangling pointers or shared state corruption.\\n4. Because all cryptographic algorithms registered by the driver look up their context using `dev_get_drvdata(sa_k3_dev)`, all subsequent crypto operations will incorrectly route to the last probed hardware instance.\",\"type\":\"Driver State / Concurrency\"},{\"description\":\"Splitting a scatterlist after it has already been mapped for DMA.\",\"locations\":[{\"code_snippet\":\"ret = sg_split(mapped_sg->sgt.sgl, mapped_sg->sgt.nents, 0, 1, &split_size, &src, &src_nents, gfp_flags);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_run\",\"line\":null,\"why_this_location_matters\":\"This executes sg_split on a scatterlist that was just successfully mapped by dma_map_sgtable, violating the DMA API constraints.\"}],\"patch_index\":29,\"patch_subject\":\"[PATCH 29/30] crypto: sa2ul - report SA engine hardware revision\",\"preexisting\":true,\"reasoning\":\"1. In sa_run(), dma_map_sgtable() maps req->src and req->dst for DMA.\\n2. Immediately after, sg_split() is called on the already mapped scatterlist to divide it based on split_size.\\n3. sg_split() only splits CPU-side lengths (sg->length) and does not adjust or calculate the dma_address and dma_length fields for the split segments (especially if the IOMMU coalesced entries).\\n4. Passing this improperly split scatterlist to dmaengine_prep_slave_sg() results in the DMA engine using corrupted or missing DMA addresses.\",\"type\":\"DMA API Violation\"},{\"description\":\"Native bitwise OR operations on a byte-swapped buffer corrupt the descriptor on Big Endian.\",\"locations\":[{\"code_snippet\":\"cmdl[upd_info->enc_size.index] |= req->enc_size;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":null,\"why_this_location_matters\":\"This line applies a native bitwise OR on the descriptor word, breaking the byte order on Big Endian systems.\"}],\"patch_index\":29,\"patch_subject\":\"[PATCH 29/30] crypto: sa2ul - report SA engine hardware revision\",\"preexisting\":true,\"reasoning\":\"1. sa_format_cmdl_gen() builds a descriptor and reverses the bytes of each u32 word using swab32(), producing an identical byte sequence in memory regardless of CPU endianness.\\n2. sa_update_cmdl() modifies this memory by accessing it as an array of native u32 words and applying bitwise operations (e.g., |= req->enc_size).\\n3. Because a native u32 maps to different memory bytes on Big Endian vs Little Endian, the bitwise OR modifies different bytes on Big Endian, incorrectly placing the size and offset values in the hardware descriptor.\",\"type\":\"Endianness Bug\"},{\"description\":\"Casting unaligned IV byte array to a u32 pointer causes undefined behavior.\",\"locations\":[{\"code_snippet\":\"data[j] = cpu_to_be32(*enc_iv);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_update_cmdl\",\"line\":null,\"why_this_location_matters\":\"This is where the potentially unaligned byte array is cast and dereferenced as a 32-bit integer.\"}],\"patch_index\":29,\"patch_subject\":\"[PATCH 29/30] crypto: sa2ul - report SA engine hardware revision\",\"preexisting\":true,\"reasoning\":\"1. In sa_update_cmdl(), req->enc_iv (a pointer to a byte array) is cast directly to a u32 pointer.\\n2. The code then dereferences it in a loop: cpu_to_be32(*enc_iv).\\n3. The incoming Initialization Vector array is not guaranteed to be 4-byte aligned, which will trigger an alignment fault (or silent corruption) on architectures lacking hardware support for unaligned word accesses.\",\"type\":\"Unaligned Memory Access\"}],\"concerns_count\":7,\"dismissed_concerns\":[{\"description\":\"Potential endianness portability issues, mixed accessors, or missing byte swaps when using `readl_relaxed()` to read the `SA_REVISION` register.\",\"locations\":[{\"code_snippet\":\"rev = readl_relaxed(saul_base + SA_REVISION);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2498,\"why_this_location_matters\":\"This is where the device register is read, correctly using the automatic endianness conversion provided by the readl_relaxed macro for a control register.\"}],\"reasoning\":\"The `io-accessors.md` guidelines warn against mixing `readsl()` and `readl()` on FIFOs, and note that `readl()` byteswaps on big-endian CPUs. However, `SA_REVISION` is a standard hardware control/status register, not a bulk data FIFO. Thus, `readl_relaxed()` correctly performs the necessary CPU-to-device byteswapping (via `__le32_to_cpu()`) to read defined bit layouts, which is the exact intended behavior. There is no mix of accessors for this address, and the endianness conversion automatically correctly handles big-endian and little-endian architectures.\",\"type\":\"Endianness / I/O Accessors\"},{\"description\":\"Potential bus error, external abort, or missing memory barrier from reading the `SA_REVISION` register before the IP block is fully active.\",\"locations\":[{\"code_snippet\":\"rev = readl_relaxed(saul_base + SA_REVISION);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2498,\"why_this_location_matters\":\"This read occurs safely and synchronously after pm_runtime_resume_and_get, ensuring the hardware state is active.\"}],\"reasoning\":\"The new `readl_relaxed` call is safely placed immediately after a successful `pm_runtime_resume_and_get(dev)` call. Since this function operates synchronously and guarantees that power domains and clocks are fully enabled upon returning success, reading `SA_REVISION` is safe and requires no additional explicit memory barrier.\",\"type\":\"Power Management / Hardware State\"},{\"description\":\"The `saul_base` pointer is declared as a `static` local variable, which could cause a race condition or incorrect pointer usage if the driver probes multiple instances concurrently.\",\"locations\":[{\"code_snippet\":\"static void __iomem *saul_base;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2466,\"why_this_location_matters\":\"This unusual static local declaration is overwritten on each entry and used locally, making it harmless in practice.\"}],\"reasoning\":\"While using `static void __iomem *saul_base;` inside a probe function is an unusual pattern, it is unconditionally overwritten by `devm_platform_ioremap_resource` upon every entry to the function and is only used locally within the serialized probe execution. It is never accessed by asynchronous callbacks, making the static storage duration harmless in practice for `saul_base` itself.\",\"type\":\"Concurrency / State Management\"},{\"description\":\"Potential resource leak of dev_data or saul_base if sa_init_mem() or later initialization steps fail.\",\"locations\":[{\"code_snippet\":\"\\tret = sa_init_mem(dev_data);\\n\\tif (ret)\\n\\t\\tgoto disable_pm;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2503,\"why_this_location_matters\":\"Shows the error path jumping to disable_pm without explicit free/unmap, which is safe due to devm_ usage.\"}],\"reasoning\":\"Both dev_data and the I/O memory mapping for saul_base are allocated using managed APIs (devm_kzalloc and devm_platform_ioremap_resource). On failure paths such as 'goto disable_pm', the driver explicitly reverts the PM runtime state, and the devres framework automatically frees the memory and unmaps the I/O region, ensuring no leak occurs.\",\"type\":\"Resource Management\"}],\"dismissed_concerns_count\":4,\"findings\":[]}","patch_id":189894,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":308522,"tokens_in":596908,"tokens_out":11605},{"baseline":{"branch":"a9d7ced84989ec05be09b4b8428759ef60450a0f","commit":"a9d7ced84989ec05be09b4b8428759ef60450a0f","repo_url":null},"created_at":1789466950,"id":167786,"inline_review":"commit c0b1b1a33153691aa48efb82c6e404ad02a37641\nAuthor: Manorit Chawdhry <m-chawdhry@ti.com>\n\ncrypto: sa2ul - add AES-CM (SA3UL_CM) TRNG priming support\n    \nThe SA3UL_CM hardware variant requires an extra AES key schedule round for\nAES-256 decryption, and needs a one-time TRNG-seeded AES-ECB priming\noperation after every power-up before its side-channel countermeasures are\nactive. This adds the extra round computation and runs a throwaway ecb(aes)\noperation to satisfy the priming requirement.\n\n> diff --git a/drivers/crypto/sa2ul.c b/drivers/crypto/sa2ul.c\n> --- a/drivers/crypto/sa2ul.c\n> +++ b/drivers/crypto/sa2ul.c\n> @@ -517,6 +529,23 @@ static inline int sa_aes_inv_key(u8 *inv_key, const u8 *key, u16 key_sz)\n>  \t\tctx.key_enc[53] = ctx.key_enc[52] ^ ctx.key_enc[47];\n>  \t}\n>  \n> +\t/*\n> +\t * SA3UL CM hardware variant needs an extra round 15 for AES-256.\n> +\t * ctx.key_enc[] only holds 60 words (rounds 0-14), so round 15 is\n> +\t * computed into a local array instead of writing past its end.\n> +\t */\n> +\tif (key_sz == AES_KEYSIZE_256 && aes_cm) {\n> +\t\tround15[0] = sa_aes_subword(ctx.key_enc[59]) ^ ctx.key_enc[52];\n> +\t\tround15[1] = round15[0] ^ ctx.key_enc[53];\n> +\t\tround15[2] = round15[1] ^ ctx.key_enc[54];\n> +\t\tround15[3] = round15[2] ^ ctx.key_enc[55];\n> +\n> +\t\t/* Decrypt key = round14 || round15 */\n> +\t\tmemcpy(inv_key, &ctx.key_enc[56], 16);\n> +\t\tmemcpy(inv_key + 16, round15, 16);\n> +\t\treturn 0;\n\n[Severity: High]\nDoes this leave the derived cryptographic key material in round15 exposed\non the kernel stack?\n\nSince round15 contains the 15th round key for AES-256, returning without\ncalling memzero_explicit() could allow a data leak if the stack memory is\nlater reused or dumped.\n\n[ ... ]\n\n> @@ -2530,6 +2620,12 @@ static int sa_ul_probe(struct platform_device *pdev)\n>  \n>  \tsa_register_algos(dev_data);\n>  \n> +\tif (dev_data->aes_cm) {\n> +\t\tret = sa_aes_cm_trng_prime(dev_data);\n\n[Severity: High]\nAre we exposing the algorithms to the system before the mandatory hardware\npriming is complete?\n\nCalling sa_register_algos() triggers cryptomgr to dispatch asynchronous\nself-tests. Because sa_aes_cm_trng_prime() then calls crypto_alloc_skcipher(),\nit blocks to wait for the larval test completion.\n\nThis causes the hardware's first operation to be predictable test vectors\nfrom cryptomgr rather than random data, defeating the DPA side-channel\ncountermeasures.\n\n> +\t\tif (ret)\n> +\t\t\tdev_warn(dev, \"aes_cm TRNG priming failed: %d\\n\", ret);\n\n[Severity: High]\nDoes this allow the probe to fail open into a vulnerable state?\n\nIf sa_aes_cm_trng_prime() returns an error (such as a memory allocation\nfailure), only a warning is logged and the probe proceeds. This leaves the\nalgorithms globally registered and the hardware active without its required\nside-channel countermeasures.\n\n> +\t}\n> +\n>  \tret = of_platform_populate(node, NULL, NULL, dev);","model":"gemini-3.1-pro-preview","output":"{\"concerns\":[],\"concerns_count\":14,\"dismissed_concerns\":[{\"description\":\"Potential deadlock by synchronously allocating and waiting for a crypto TFM in the driver probe function.\",\"locations\":[{\"code_snippet\":\"\\ttfm = crypto_alloc_skcipher(\\\"ecb-aes-sa2ul\\\", 0, 0);\\n\\tif (IS_ERR(tfm)) {\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2517,\"why_this_location_matters\":\"This is the synchronous allocation that blocks on the cryptomgr test, but does not cause a deadlock.\"},{\"code_snippet\":\"\\t\\tret = sa_aes_cm_trng_prime(dev_data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2623,\"why_this_location_matters\":\"Occurs after `crypto_engine_start()`, ensuring requests can be asynchronously dequeued and processed.\"}],\"reasoning\":\"While `crypto_alloc_skcipher()` waits for the algorithm to be self-tested by `cryptomgr`, the test thread runs independently on the `cryptomgr_wq` workqueue. The driver's hardware processing is also handled asynchronously by the `crypto_engine` thread, which is started before the priming request. Because `sa_ul_probe()` does not hold any locks required by these worker threads, they can complete and safely wake up the probe function without deadlocking.\",\"type\":\"Deadlock\"},{\"description\":\"Possible endianness bug in `sa_aes_subword()` causing incorrect AES round key derivation on big-endian or little-endian systems.\",\"locations\":[{\"code_snippet\":\"\\treturn (u32)crypto_aes_sbox[w & 0xff] |\\n\\t       ((u32)crypto_aes_sbox[(w >> 8) & 0xff] << 8) |\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_subword\",\"line\":506,\"why_this_location_matters\":\"Demonstrates that the substitution acts logically on the u32 integer, making it endian-agnostic.\"}],\"reasoning\":\"The `ctx.key_enc` array is populated by `aes_expandkey()`, which stores the round keys as host-endian `u32` values. `sa_aes_subword()` performs byte-wise S-box substitution using bitwise shifts on logical `u32` variables. Because operations act logically on the integer value rather than physical byte pointers, the correct logical bytes are substituted regardless of host endianness.\",\"type\":\"Logic Error\"},{\"description\":\"The plaintext buffer `pt` is allocated with `kmalloc`, used in place, and freed without being zeroized.\",\"locations\":[{\"code_snippet\":\"\\tmemzero_explicit(key, sizeof(key));\\n\\tkfree(pt);\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2552,\"why_this_location_matters\":\"Shows where `pt` is freed without zeroization, which is safe because it only ever holds random noise.\"}],\"reasoning\":\"The buffer `pt` is populated with purely random bytes to serve as throwaway plaintext for the hardware TRNG priming process. The resulting ciphertext is also random noise. Since the buffer never holds sensitive secrets or derived keys, zeroizing it before `kfree()` is unnecessary.\",\"type\":\"Data Leak\"},{\"description\":\"Possible Use-After-Free or DMA corruption from mapping a stack-allocated `struct scatterlist sg` for asynchronous hardware operations.\",\"locations\":[{\"code_snippet\":\"\\tstruct scatterlist sg;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2502,\"why_this_location_matters\":\"This stack allocation was analyzed to determine if it could cause DMA issues during the hardware operation.\"},{\"code_snippet\":\"\\tret = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2535,\"why_this_location_matters\":\"This synchronous wait guarantees that the stack frame is not popped before the DMA and crypto operations complete.\"}],\"reasoning\":\"Although `sg` is allocated on the stack, `sa_aes_cm_trng_prime()` synchronously blocks on the crypto operation via `crypto_wait_req()`. The wait guarantees the stack frame remains alive and valid until the hardware has completed all transfers and the scatterlist is unmapped, making it fully safe for DMA.\",\"type\":\"DMA / Scatterlist\"},{\"description\":\"Possible memory or resource leak on error paths during TRNG priming in `sa_aes_cm_trng_prime()`.\",\"locations\":[{\"code_snippet\":\"free_req:\\n\\tskcipher_request_free(req);\\nfree_tfm:\\n\\tcrypto_free_skcipher(tfm);\\nout_zero:\\n\\tmemzero_explicit(key, sizeof(key));\\n\\tkfree(pt);\\n\\treturn ret;\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2538,\"why_this_location_matters\":\"This error handling block verifies that all allocated resources are systematically cleaned up on failure.\"}],\"reasoning\":\"The function handles cleanup correctly through a centralized, reverse-order `goto` label chain. On all paths, `req` and `tfm` are properly destroyed, `pt` is unconditionally freed via `kfree()`, and the stack-allocated `key` array is zeroized via `memzero_explicit()`.\",\"type\":\"Resource Management\"},{\"description\":\"Potential buffer overflow when writing `round15` to `inv_key + 16`.\",\"locations\":[{\"code_snippet\":\"\\t\\tmemcpy(inv_key + 16, round15, 16);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_inv_key\",\"line\":544,\"why_this_location_matters\":\"This confirms the safe boundaries for writing the extra 16 bytes for round 15 into the DMA-mapped context buffer.\"}],\"reasoning\":\"The destination `inv_key` points to `&sc_buf[SC_ENC_KEY_OFFSET]`. `sc_buf` is dynamically allocated with `SA_CTX_MAX_SZ`, which provides ample space for the full hardware cryptographic context. Writing exactly 32 bytes (16 for round14 and 16 for round15) fits securely within the buffer's allocated capacity.\",\"type\":\"Logic Error\"},{\"description\":\"Potential endianness mismatch when copying `round15` to `inv_key` via `memcpy` on big-endian architectures.\",\"locations\":[{\"code_snippet\":\"\\t\\tmemcpy(inv_key + 16, round15, 16);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_inv_key\",\"line\":543,\"why_this_location_matters\":\"This is where the byte copy occurs from native words, identically to pre-existing code logic.\"}],\"reasoning\":\"While `memcpy` of host `u32` array elements to a byte array produces byte-swapped results on big-endian systems, this exact pattern is identical to the pre-existing logic for AES-128/192/256 inverse key copies. Furthermore, supported K3 SoCs configurations are exclusively little-endian.\",\"type\":\"Hardware/Architecture Specific Bug\"},{\"description\":\"Sleepable functions like `kmalloc(GFP_KERNEL)` and `crypto_wait_req()` are called in `sa_aes_cm_trng_prime()` without verifying execution context.\",\"locations\":[{\"code_snippet\":\"\\tpt = kmalloc(AES_BLOCK_SIZE, GFP_KERNEL);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2507,\"why_this_location_matters\":\"This allocation correctly uses GFP_KERNEL because the probe context allows sleeping.\"}],\"reasoning\":\"The priming function is strictly invoked from the `sa_ul_probe()` context. Because platform device probe functions execute in a sleepable worker thread without holding atomic spinlocks or RCU read locks, it is perfectly safe to perform blocking allocations and waits.\",\"type\":\"Sleeping in Atomic Context\"},{\"description\":\"Allocating a 16-byte buffer for DMA using `kmalloc()` might cause cacheline sharing or safety issues on non-coherent architectures.\",\"locations\":[{\"code_snippet\":\"\\tpt = kmalloc(AES_BLOCK_SIZE, GFP_KERNEL);\\n\\tif (!pt)\\n\\t\\treturn -ENOMEM;\\n\\n\\tget_random_bytes(key, sizeof(key));\\n\\tget_random_bytes(pt, AES_BLOCK_SIZE);\\n...\\n\\tsg_init_one(&sg, pt, AES_BLOCK_SIZE);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2508,\"why_this_location_matters\":\"This verifies that the dynamically allocated memory is safe for the `sg_init_one()` and subsequent async hardware DMA operation.\"}],\"reasoning\":\"Standalone memory allocated via `kmalloc()` is either padded/aligned to `ARCH_DMA_MINALIGN` or safely bounce-buffered via `CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC`. Thus, handing off an independent 16-byte `kmalloc` buffer to the scatterlist DMA API is protected against adjacent memory corruption.\",\"type\":\"DMA Mapping Safety\"}],\"dismissed_concerns_count\":9,\"findings\":[{\"locations\":[{\"code_snippet\":\"\\tu32 round15[4];\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_inv_key\",\"line\":519,\"why_this_location_matters\":\"This declares the local stack array that temporarily holds the derived sensitive cryptographic key material.\"},{\"code_snippet\":\"\\t\\tmemcpy(inv_key + 16, round15, 16);\\n\\t\\treturn 0;\\n\\t}\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_inv_key\",\"line\":542,\"why_this_location_matters\":\"The function returns immediately after using `round15` without calling `memzero_explicit(round15, sizeof(round15));`.\"}],\"patch_index\":30,\"patch_subject\":\"[PATCH 30/30] crypto: sa2ul - add AES-CM (SA3UL_CM) TRNG priming support\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: AES-256 decryption key left unzeroized on stack\",\"severity\":\"High\",\"severity_explanation\":\"Consequence: Cryptographic key material (the extra AES-256 15th round key) is left exposed on the kernel stack, creating a data leak vulnerability. Triggering path: Any AES-256 decryption operation on the SA3UL_CM hardware variant populates the `round15` array and returns without zeroizing it. Reachability: Reachable by any user triggering AES-256 decryption. Leaving key material on the stack is a strict violation of cryptographic safety standards.\"},{\"locations\":[{\"code_snippet\":\"\\tsa_register_algos(dev_data);\\n\\n\\tif (dev_data->aes_cm) {\\n\\t\\tret = sa_aes_cm_trng_prime(dev_data);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2618,\"why_this_location_matters\":\"Algorithms are exposed to the system and `cryptomgr` self-tests before the mandatory hardware priming is dispatched.\"},{\"code_snippet\":\"\\ttfm = crypto_alloc_skcipher(\\\"ecb-aes-sa2ul\\\", 0, 0);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_aes_cm_trng_prime\",\"line\":2517,\"why_this_location_matters\":\"This API call waits on the larval test completion, yielding the hardware's critical first operation to the `cryptomgr` predictable test vectors.\"}],\"patch_index\":30,\"patch_subject\":\"[PATCH 30/30] crypto: sa2ul - add AES-CM (SA3UL_CM) TRNG priming support\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: TRNG priming race with cryptomgr self-tests\",\"severity\":\"High\",\"severity_explanation\":\"Consequence: The hardware TRNG is primed with predictable test vectors instead of random data, defeating its DPA side-channel countermeasures. Triggering path: In `sa_ul_probe()`, `sa_register_algos()` is called before `sa_aes_cm_trng_prime()`. Registering algorithms triggers the `cryptomgr` to dispatch asynchronous self-tests. The priming function then uses `crypto_alloc_skcipher()`, which blocks until those self-tests complete. Reachability: Happens deterministically on every probe. By the time the random priming vector is submitted, the hardware has already processed fixed test vectors, compromising the hardware's security mechanism.\"},{\"locations\":[{\"code_snippet\":\"\\t\\tret = sa_aes_cm_trng_prime(dev_data);\\n\\t\\tif (ret)\\n\\t\\t\\tdev_warn(dev, \\\"aes_cm TRNG priming failed: %d\\\\n\\\", ret);\",\"file\":\"drivers/crypto/sa2ul.c\",\"function_or_symbol\":\"sa_ul_probe\",\"line\":2623,\"why_this_location_matters\":\"The probe logic catches the priming failure but deliberately ignores it, enabling the fail-open behavior without unregistering the algorithms.\"}],\"patch_index\":30,\"patch_subject\":\"[PATCH 30/30] crypto: sa2ul - add AES-CM (SA3UL_CM) TRNG priming support\",\"preexisting\":false,\"problem\":\"crypto: sa2ul: probe fails open on TRNG hardware priming failure\",\"severity\":\"High\",\"severity_explanation\":\"Consequence: The hardware remains active and accessible but without its required side-channel countermeasures, failing open into a vulnerable state. Triggering path: If `sa_aes_cm_trng_prime()` returns an error (e.g., due to a memory allocation failure in `kmalloc` or `crypto_alloc_skcipher`), `sa_ul_probe()` merely logs a warning and proceeds to return 0 (success). Reachability: A local unprivileged user could induce memory pressure to cause the priming allocation to fail during probe, leaving the hardware algorithms (which were already registered globally) exposed in a degraded security state.\"}]}","patch_id":189893,"prompts_hash":"0.4.0","provider":"gemini","result":"Review completed successfully.","status":"Reviewed","summary":"","tokens_cached":3306808,"tokens_in":4123411,"tokens_out":25358}],"slug":null,"smtp_enabled":true,"status":"Reviewed","subject":"[PATCH 00/30] Clean and improve SA2UL driver","subsystems":["LKML","linux-crypto"],"thread":[{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466106,"id":519582,"in_reply_to":null,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","subject":"[PATCH 00/30] Clean and improve SA2UL driver"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466107,"id":519587,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-1-57ab34e97162@ti.com","subject":"[PATCH 01/30] crypto: sa2ul - remove dead code"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466108,"id":519588,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-2-57ab34e97162@ti.com","subject":"[PATCH 02/30] crypto: sa2ul - remove totally unused structure fields"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466109,"id":519589,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-3-57ab34e97162@ti.com","subject":"[PATCH 03/30] crypto: sa2ul - remove unused algorithm ID fields"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466110,"id":519583,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-4-57ab34e97162@ti.com","subject":"[PATCH 04/30] crypto: sa2ul - remove unused fields from sa_cmdl_cfg"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466111,"id":519584,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-5-57ab34e97162@ti.com","subject":"[PATCH 05/30] crypto: sa2ul - remove unused fields from sa_tfm_ctx"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466112,"id":519585,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-6-57ab34e97162@ti.com","subject":"[PATCH 06/30] crypto: sa2ul - remove unused macro definitions"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466113,"id":519590,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-7-57ab34e97162@ti.com","subject":"[PATCH 07/30] crypto: sa2ul - consolidate encryption offset definitions"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466114,"id":519592,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-8-57ab34e97162@ti.com","subject":"[PATCH 08/30] crypto: sa2ul - remove unused SC ID range tracking"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466115,"id":519594,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-9-57ab34e97162@ti.com","subject":"[PATCH 09/30] crypto: sa2ul - remove unused base register pointer"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466116,"id":519595,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-10-57ab34e97162@ti.com","subject":"[PATCH 10/30] crypto: sa2ul - remove unused includes and defines"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466117,"id":519586,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-11-57ab34e97162@ti.com","subject":"[PATCH 11/30] crypto: sa2ul - remove unused line"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466118,"id":519605,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-12-57ab34e97162@ti.com","subject":"[PATCH 12/30] crypto: sa2ul - remove redundant sa_sha_digest() wrapper"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466119,"id":519600,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-13-57ab34e97162@ti.com","subject":"[PATCH 13/30] crypto: sa2ul - fix struct documentation for match_data"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466120,"id":519604,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-14-57ab34e97162@ti.com","subject":"[PATCH 14/30] crypto: sa2ul - zero out security context on free"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466121,"id":519593,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-15-57ab34e97162@ti.com","subject":"[PATCH 15/30] crypto: sa2ul - fix context release on errors"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466122,"id":519599,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-16-57ab34e97162@ti.com","subject":"[PATCH 16/30] crypto: sa2ul - fix resource leak of sha in init_alg() error path"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466123,"id":519598,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-17-57ab34e97162@ti.com","subject":"[PATCH 17/30] crypto: sa2ul - fix resource leak of AEAD in init_alg() error path"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466124,"id":519601,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-18-57ab34e97162@ti.com","subject":"[PATCH 18/30] crypto: sa2ul - fix DMA mapping leak in sa_run() error paths"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466125,"id":519603,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-19-57ab34e97162@ti.com","subject":"[PATCH 19/30] crypto: sa2ul - generate dynamic metadata length"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466126,"id":519610,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-20-57ab34e97162@ti.com","subject":"[PATCH 20/30] crypto: sa2ul - fix command label stack corruption"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466127,"id":519602,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-21-57ab34e97162@ti.com","subject":"[PATCH 21/30] crypto: sa2ul - fix error handling in sa_prepare_iopad"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466128,"id":519607,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-22-57ab34e97162@ti.com","subject":"[PATCH 22/30] crypto: sa2ul - move export to appropriate location."},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466129,"id":519608,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-23-57ab34e97162@ti.com","subject":"[PATCH 23/30] crypto: sa2ul - fix stack overflow in sa_prepare_iopads"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466130,"id":519613,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-24-57ab34e97162@ti.com","subject":"[PATCH 24/30] crypto: sa2ul - add more checks before processing ipad/opad"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466131,"id":519606,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-25-57ab34e97162@ti.com","subject":"[PATCH 25/30] crypto: sa2ul - fix data corruption by skipping device sync on unmap"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466132,"id":519614,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-26-57ab34e97162@ti.com","subject":"[PATCH 26/30] crypto: sa2ul - use correct DMA direction in sa_sync_from_device"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466133,"id":519609,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-27-57ab34e97162@ti.com","subject":"[PATCH 27/30] crypto: sa2ul - change dma_alloc_pool to mempool"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466134,"id":519618,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-28-57ab34e97162@ti.com","subject":"[PATCH 28/30] crypto: sa2ul - route requests through crypto_engine"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466135,"id":519617,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-29-57ab34e97162@ti.com","subject":"[PATCH 29/30] crypto: sa2ul - report SA engine hardware revision"},{"author":"\"Manorit Chawdhry\" <m-chawdhry@ti.com>","date":1789466136,"id":519616,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-30-57ab34e97162@ti.com","subject":"[PATCH 30/30] crypto: sa2ul - add AES-CM (SA3UL_CM) TRNG priming support"},{"author":"\"T Pratham\" <t-pratham@ti.com>","date":1789639512,"id":529533,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-28-57ab34e97162@ti.com","message_id":"77e34131-04a3-46c4-9248-a35bb867e9c5@ti.com","subject":"Re: [PATCH 28/30] crypto: sa2ul - route requests through crypto_engine"},{"author":"\"T Pratham\" <t-pratham@ti.com>","date":1789640025,"id":529558,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-23-57ab34e97162@ti.com","message_id":"dfddf92e-1547-4cad-94c4-b5fbba098134@ti.com","subject":"Re: [PATCH 23/30] crypto: sa2ul - fix stack overflow in sa_prepare_iopads"},{"author":"\"Herbert Xu\" <herbert@gondor.apana.org.au>","date":1790140572,"id":551726,"in_reply_to":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","message_id":"arNgnMuKPAHYxP4Y@gondor.apana.org.au","subject":"Re: [PATCH 00/30] Clean and improve SA2UL driver"}],"to":"\"Herbert Xu\" <herbert@gondor.apana.org.au>, \"David S. Miller\" <davem@davemloft.net>, \"Keerthy\" <j-keerthy@ti.com>, \"Colin Ian King\" <colin.i.king@gmail.com>","total_parts":30,"total_patches_in_db":30,"version":1,"version_link_signal":null,"versions":[{"date":1789466150,"id":74414,"message_id":"20260915-b4-upstream-sa2ul-cleanup-v1-0-57ab34e97162@ti.com","slug":null,"status":"Reviewed","subject":"[PATCH 00/30] Clean and improve SA2UL driver","version":1},{"date":1793771080,"id":102088,"message_id":"20261104-b4-upstream-sa2ul-cleanup-v2-0-15ab90b3f9c2@ti.com","slug":null,"status":"Reviewed","subject":"[PATCH v2 00/30] Clean and improve SA2UL driver","version":2}]}