Path: blob/master/drivers/accel/habanalabs/common/command_submission.c
26436 views
// SPDX-License-Identifier: GPL-2.012/*3* Copyright 2016-2021 HabanaLabs, Ltd.4* All Rights Reserved.5*/67#include <uapi/drm/habanalabs_accel.h>8#include "habanalabs.h"910#include <linux/uaccess.h>11#include <linux/slab.h>1213#define HL_CS_FLAGS_TYPE_MASK (HL_CS_FLAGS_SIGNAL | HL_CS_FLAGS_WAIT | \14HL_CS_FLAGS_COLLECTIVE_WAIT | HL_CS_FLAGS_RESERVE_SIGNALS_ONLY | \15HL_CS_FLAGS_UNRESERVE_SIGNALS_ONLY | HL_CS_FLAGS_ENGINE_CORE_COMMAND | \16HL_CS_FLAGS_ENGINES_COMMAND | HL_CS_FLAGS_FLUSH_PCI_HBW_WRITES)171819#define MAX_TS_ITER_NUM 1002021/**22* enum hl_cs_wait_status - cs wait status23* @CS_WAIT_STATUS_BUSY: cs was not completed yet24* @CS_WAIT_STATUS_COMPLETED: cs completed25* @CS_WAIT_STATUS_GONE: cs completed but fence is already gone26*/27enum hl_cs_wait_status {28CS_WAIT_STATUS_BUSY,29CS_WAIT_STATUS_COMPLETED,30CS_WAIT_STATUS_GONE31};3233/*34* Data used while handling wait/timestamp nodes.35* The purpose of this struct is to store the needed data for both operations36* in one variable instead of passing large number of arguments to functions.37*/38struct wait_interrupt_data {39struct hl_user_interrupt *interrupt;40struct hl_mmap_mem_buf *buf;41struct hl_mem_mgr *mmg;42struct hl_cb *cq_cb;43u64 ts_handle;44u64 ts_offset;45u64 cq_handle;46u64 cq_offset;47u64 target_value;48u64 intr_timeout_us;49};5051static void job_wq_completion(struct work_struct *work);52static int _hl_cs_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx, u64 timeout_us, u64 seq,53enum hl_cs_wait_status *status, s64 *timestamp);54static void cs_do_release(struct kref *ref);5556static void hl_push_cs_outcome(struct hl_device *hdev,57struct hl_cs_outcome_store *outcome_store,58u64 seq, ktime_t ts, int error)59{60struct hl_cs_outcome *node;61unsigned long flags;6263/*64* CS outcome store supports the following operations:65* push outcome - store a recent CS outcome in the store66* pop outcome - retrieve a SPECIFIC (by seq) CS outcome from the store67* It uses 2 lists: used list and free list.68* It has a pre-allocated amount of nodes, each node stores69* a single CS outcome.70* Initially, all the nodes are in the free list.71* On push outcome, a node (any) is taken from the free list, its72* information is filled in, and the node is moved to the used list.73* It is possible, that there are no nodes left in the free list.74* In this case, we will lose some information about old outcomes. We75* will pop the OLDEST node from the used list, and make it free.76* On pop, the node is searched for in the used list (using a search77* index).78* If found, the node is then removed from the used list, and moved79* back to the free list. The outcome data that the node contained is80* returned back to the user.81*/8283spin_lock_irqsave(&outcome_store->db_lock, flags);8485if (list_empty(&outcome_store->free_list)) {86node = list_last_entry(&outcome_store->used_list,87struct hl_cs_outcome, list_link);88hash_del(&node->map_link);89dev_dbg(hdev->dev, "CS %llu outcome was lost\n", node->seq);90} else {91node = list_last_entry(&outcome_store->free_list,92struct hl_cs_outcome, list_link);93}9495list_del_init(&node->list_link);9697node->seq = seq;98node->ts = ts;99node->error = error;100101list_add(&node->list_link, &outcome_store->used_list);102hash_add(outcome_store->outcome_map, &node->map_link, node->seq);103104spin_unlock_irqrestore(&outcome_store->db_lock, flags);105}106107static bool hl_pop_cs_outcome(struct hl_cs_outcome_store *outcome_store,108u64 seq, ktime_t *ts, int *error)109{110struct hl_cs_outcome *node;111unsigned long flags;112113spin_lock_irqsave(&outcome_store->db_lock, flags);114115hash_for_each_possible(outcome_store->outcome_map, node, map_link, seq)116if (node->seq == seq) {117*ts = node->ts;118*error = node->error;119120hash_del(&node->map_link);121list_del_init(&node->list_link);122list_add(&node->list_link, &outcome_store->free_list);123124spin_unlock_irqrestore(&outcome_store->db_lock, flags);125126return true;127}128129spin_unlock_irqrestore(&outcome_store->db_lock, flags);130131return false;132}133134static void hl_sob_reset(struct kref *ref)135{136struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob,137kref);138struct hl_device *hdev = hw_sob->hdev;139140dev_dbg(hdev->dev, "reset sob id %u\n", hw_sob->sob_id);141142hdev->asic_funcs->reset_sob(hdev, hw_sob);143144hw_sob->need_reset = false;145}146147void hl_sob_reset_error(struct kref *ref)148{149struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob,150kref);151struct hl_device *hdev = hw_sob->hdev;152153dev_crit(hdev->dev,154"SOB release shouldn't be called here, q_idx: %d, sob_id: %d\n",155hw_sob->q_idx, hw_sob->sob_id);156}157158void hw_sob_put(struct hl_hw_sob *hw_sob)159{160if (hw_sob)161kref_put(&hw_sob->kref, hl_sob_reset);162}163164static void hw_sob_put_err(struct hl_hw_sob *hw_sob)165{166if (hw_sob)167kref_put(&hw_sob->kref, hl_sob_reset_error);168}169170void hw_sob_get(struct hl_hw_sob *hw_sob)171{172if (hw_sob)173kref_get(&hw_sob->kref);174}175176/**177* hl_gen_sob_mask() - Generates a sob mask to be used in a monitor arm packet178* @sob_base: sob base id179* @sob_mask: sob user mask, each bit represents a sob offset from sob base180* @mask: generated mask181*182* Return: 0 if given parameters are valid183*/184int hl_gen_sob_mask(u16 sob_base, u8 sob_mask, u8 *mask)185{186int i;187188if (sob_mask == 0)189return -EINVAL;190191if (sob_mask == 0x1) {192*mask = ~(1 << (sob_base & 0x7));193} else {194/* find msb in order to verify sob range is valid */195for (i = BITS_PER_BYTE - 1 ; i >= 0 ; i--)196if (BIT(i) & sob_mask)197break;198199if (i > (HL_MAX_SOBS_PER_MONITOR - (sob_base & 0x7) - 1))200return -EINVAL;201202*mask = ~sob_mask;203}204205return 0;206}207208static void hl_fence_release(struct kref *kref)209{210struct hl_fence *fence =211container_of(kref, struct hl_fence, refcount);212struct hl_cs_compl *hl_cs_cmpl =213container_of(fence, struct hl_cs_compl, base_fence);214215kfree(hl_cs_cmpl);216}217218void hl_fence_put(struct hl_fence *fence)219{220if (IS_ERR_OR_NULL(fence))221return;222kref_put(&fence->refcount, hl_fence_release);223}224225void hl_fences_put(struct hl_fence **fence, int len)226{227int i;228229for (i = 0; i < len; i++, fence++)230hl_fence_put(*fence);231}232233void hl_fence_get(struct hl_fence *fence)234{235if (fence)236kref_get(&fence->refcount);237}238239static void hl_fence_init(struct hl_fence *fence, u64 sequence)240{241kref_init(&fence->refcount);242fence->cs_sequence = sequence;243fence->error = 0;244fence->timestamp = ktime_set(0, 0);245fence->mcs_handling_done = false;246init_completion(&fence->completion);247}248249void cs_get(struct hl_cs *cs)250{251kref_get(&cs->refcount);252}253254static int cs_get_unless_zero(struct hl_cs *cs)255{256return kref_get_unless_zero(&cs->refcount);257}258259static void cs_put(struct hl_cs *cs)260{261kref_put(&cs->refcount, cs_do_release);262}263264static void cs_job_do_release(struct kref *ref)265{266struct hl_cs_job *job = container_of(ref, struct hl_cs_job, refcount);267268kfree(job);269}270271static void hl_cs_job_put(struct hl_cs_job *job)272{273kref_put(&job->refcount, cs_job_do_release);274}275276bool cs_needs_completion(struct hl_cs *cs)277{278/* In case this is a staged CS, only the last CS in sequence should279* get a completion, any non staged CS will always get a completion280*/281if (cs->staged_cs && !cs->staged_last)282return false;283284return true;285}286287bool cs_needs_timeout(struct hl_cs *cs)288{289/* In case this is a staged CS, only the first CS in sequence should290* get a timeout, any non staged CS will always get a timeout291*/292if (cs->staged_cs && !cs->staged_first)293return false;294295return true;296}297298static bool is_cb_patched(struct hl_device *hdev, struct hl_cs_job *job)299{300/* Patched CB is created for external queues jobs */301return (job->queue_type == QUEUE_TYPE_EXT);302}303304/*305* cs_parser - parse the user command submission306*307* @hpriv : pointer to the private data of the fd308* @job : pointer to the job that holds the command submission info309*310* The function parses the command submission of the user. It calls the311* ASIC specific parser, which returns a list of memory blocks to send312* to the device as different command buffers313*314*/315static int cs_parser(struct hl_fpriv *hpriv, struct hl_cs_job *job)316{317struct hl_device *hdev = hpriv->hdev;318struct hl_cs_parser parser;319int rc;320321parser.ctx_id = job->cs->ctx->asid;322parser.cs_sequence = job->cs->sequence;323parser.job_id = job->id;324325parser.hw_queue_id = job->hw_queue_id;326parser.job_userptr_list = &job->userptr_list;327parser.patched_cb = NULL;328parser.user_cb = job->user_cb;329parser.user_cb_size = job->user_cb_size;330parser.queue_type = job->queue_type;331parser.is_kernel_allocated_cb = job->is_kernel_allocated_cb;332job->patched_cb = NULL;333parser.completion = cs_needs_completion(job->cs);334335rc = hdev->asic_funcs->cs_parser(hdev, &parser);336337if (is_cb_patched(hdev, job)) {338if (!rc) {339job->patched_cb = parser.patched_cb;340job->job_cb_size = parser.patched_cb_size;341job->contains_dma_pkt = parser.contains_dma_pkt;342atomic_inc(&job->patched_cb->cs_cnt);343}344345/*346* Whether the parsing worked or not, we don't need the347* original CB anymore because it was already parsed and348* won't be accessed again for this CS349*/350atomic_dec(&job->user_cb->cs_cnt);351hl_cb_put(job->user_cb);352job->user_cb = NULL;353} else if (!rc) {354job->job_cb_size = job->user_cb_size;355}356357return rc;358}359360static void hl_complete_job(struct hl_device *hdev, struct hl_cs_job *job)361{362struct hl_cs *cs = job->cs;363364if (is_cb_patched(hdev, job)) {365hl_userptr_delete_list(hdev, &job->userptr_list);366367/*368* We might arrive here from rollback and patched CB wasn't369* created, so we need to check it's not NULL370*/371if (job->patched_cb) {372atomic_dec(&job->patched_cb->cs_cnt);373hl_cb_put(job->patched_cb);374}375}376377/* For H/W queue jobs, if a user CB was allocated by driver,378* the user CB isn't released in cs_parser() and thus should be379* released here. This is also true for INT queues jobs which were380* allocated by driver.381*/382if (job->is_kernel_allocated_cb &&383(job->queue_type == QUEUE_TYPE_HW || job->queue_type == QUEUE_TYPE_INT)) {384atomic_dec(&job->user_cb->cs_cnt);385hl_cb_put(job->user_cb);386}387388/*389* This is the only place where there can be multiple threads390* modifying the list at the same time391*/392spin_lock(&cs->job_lock);393list_del(&job->cs_node);394spin_unlock(&cs->job_lock);395396hl_debugfs_remove_job(hdev, job);397398/* We decrement reference only for a CS that gets completion399* because the reference was incremented only for this kind of CS400* right before it was scheduled.401*402* In staged submission, only the last CS marked as 'staged_last'403* gets completion, hence its release function will be called from here.404* As for all the rest CS's in the staged submission which do not get405* completion, their CS reference will be decremented by the406* 'staged_last' CS during the CS release flow.407* All relevant PQ CI counters will be incremented during the CS release408* flow by calling 'hl_hw_queue_update_ci'.409*/410if (cs_needs_completion(cs) &&411(job->queue_type == QUEUE_TYPE_EXT || job->queue_type == QUEUE_TYPE_HW)) {412413/* In CS based completions, the timestamp is already available,414* so no need to extract it from job415*/416if (hdev->asic_prop.completion_mode == HL_COMPLETION_MODE_JOB)417cs->completion_timestamp = job->timestamp;418419cs_put(cs);420}421422hl_cs_job_put(job);423}424425/*426* hl_staged_cs_find_first - locate the first CS in this staged submission427*428* @hdev: pointer to device structure429* @cs_seq: staged submission sequence number430*431* @note: This function must be called under 'hdev->cs_mirror_lock'432*433* Find and return a CS pointer with the given sequence434*/435struct hl_cs *hl_staged_cs_find_first(struct hl_device *hdev, u64 cs_seq)436{437struct hl_cs *cs;438439list_for_each_entry_reverse(cs, &hdev->cs_mirror_list, mirror_node)440if (cs->staged_cs && cs->staged_first &&441cs->sequence == cs_seq)442return cs;443444return NULL;445}446447/*448* is_staged_cs_last_exists - returns true if the last CS in sequence exists449*450* @hdev: pointer to device structure451* @cs: staged submission member452*453*/454bool is_staged_cs_last_exists(struct hl_device *hdev, struct hl_cs *cs)455{456struct hl_cs *last_entry;457458last_entry = list_last_entry(&cs->staged_cs_node, struct hl_cs,459staged_cs_node);460461if (last_entry->staged_last)462return true;463464return false;465}466467/*468* staged_cs_get - get CS reference if this CS is a part of a staged CS469*470* @hdev: pointer to device structure471* @cs: current CS472* @cs_seq: staged submission sequence number473*474* Increment CS reference for every CS in this staged submission except for475* the CS which get completion.476*/477static void staged_cs_get(struct hl_device *hdev, struct hl_cs *cs)478{479/* Only the last CS in this staged submission will get a completion.480* We must increment the reference for all other CS's in this481* staged submission.482* Once we get a completion we will release the whole staged submission.483*/484if (!cs->staged_last)485cs_get(cs);486}487488/*489* staged_cs_put - put a CS in case it is part of staged submission490*491* @hdev: pointer to device structure492* @cs: CS to put493*494* This function decrements a CS reference (for a non completion CS)495*/496static void staged_cs_put(struct hl_device *hdev, struct hl_cs *cs)497{498/* We release all CS's in a staged submission except the last499* CS which we have never incremented its reference.500*/501if (!cs_needs_completion(cs))502cs_put(cs);503}504505static void cs_handle_tdr(struct hl_device *hdev, struct hl_cs *cs)506{507struct hl_cs *next = NULL, *iter, *first_cs;508509if (!cs_needs_timeout(cs))510return;511512spin_lock(&hdev->cs_mirror_lock);513514/* We need to handle tdr only once for the complete staged submission.515* Hence, we choose the CS that reaches this function first which is516* the CS marked as 'staged_last'.517* In case single staged cs was submitted which has both first and last518* indications, then "cs_find_first" below will return NULL, since we519* removed the cs node from the list before getting here,520* in such cases just continue with the cs to cancel it's TDR work.521*/522if (cs->staged_cs && cs->staged_last) {523first_cs = hl_staged_cs_find_first(hdev, cs->staged_sequence);524if (first_cs)525cs = first_cs;526}527528spin_unlock(&hdev->cs_mirror_lock);529530/* Don't cancel TDR in case this CS was timedout because we might be531* running from the TDR context532*/533if (cs->timedout || hdev->timeout_jiffies == MAX_SCHEDULE_TIMEOUT)534return;535536if (cs->tdr_active)537cancel_delayed_work_sync(&cs->work_tdr);538539spin_lock(&hdev->cs_mirror_lock);540541/* queue TDR for next CS */542list_for_each_entry(iter, &hdev->cs_mirror_list, mirror_node)543if (cs_needs_timeout(iter)) {544next = iter;545break;546}547548if (next && !next->tdr_active) {549next->tdr_active = true;550schedule_delayed_work(&next->work_tdr, next->timeout_jiffies);551}552553spin_unlock(&hdev->cs_mirror_lock);554}555556/*557* force_complete_multi_cs - complete all contexts that wait on multi-CS558*559* @hdev: pointer to habanalabs device structure560*/561static void force_complete_multi_cs(struct hl_device *hdev)562{563int i;564565for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {566struct multi_cs_completion *mcs_compl;567568mcs_compl = &hdev->multi_cs_completion[i];569570spin_lock(&mcs_compl->lock);571572if (!mcs_compl->used) {573spin_unlock(&mcs_compl->lock);574continue;575}576577/* when calling force complete no context should be waiting on578* multi-cS.579* We are calling the function as a protection for such case580* to free any pending context and print error message581*/582dev_err(hdev->dev,583"multi-CS completion context %d still waiting when calling force completion\n",584i);585complete_all(&mcs_compl->completion);586spin_unlock(&mcs_compl->lock);587}588}589590/*591* complete_multi_cs - complete all waiting entities on multi-CS592*593* @hdev: pointer to habanalabs device structure594* @cs: CS structure595* The function signals a waiting entity that has an overlapping stream masters596* with the completed CS.597* For example:598* - a completed CS worked on stream master QID 4, multi CS completion599* is actively waiting on stream master QIDs 3, 5. don't send signal as no600* common stream master QID601* - a completed CS worked on stream master QID 4, multi CS completion602* is actively waiting on stream master QIDs 3, 4. send signal as stream603* master QID 4 is common604*/605static void complete_multi_cs(struct hl_device *hdev, struct hl_cs *cs)606{607struct hl_fence *fence = cs->fence;608int i;609610/* in case of multi CS check for completion only for the first CS */611if (cs->staged_cs && !cs->staged_first)612return;613614for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {615struct multi_cs_completion *mcs_compl;616617mcs_compl = &hdev->multi_cs_completion[i];618if (!mcs_compl->used)619continue;620621spin_lock(&mcs_compl->lock);622623/*624* complete if:625* 1. still waiting for completion626* 2. the completed CS has at least one overlapping stream627* master with the stream masters in the completion628*/629if (mcs_compl->used &&630(fence->stream_master_qid_map &631mcs_compl->stream_master_qid_map)) {632/* extract the timestamp only of first completed CS */633if (!mcs_compl->timestamp)634mcs_compl->timestamp = ktime_to_ns(fence->timestamp);635636complete_all(&mcs_compl->completion);637638/*639* Setting mcs_handling_done inside the lock ensures640* at least one fence have mcs_handling_done set to641* true before wait for mcs finish. This ensures at642* least one CS will be set as completed when polling643* mcs fences.644*/645fence->mcs_handling_done = true;646}647648spin_unlock(&mcs_compl->lock);649}650/* In case CS completed without mcs completion initialized */651fence->mcs_handling_done = true;652}653654static inline void cs_release_sob_reset_handler(struct hl_device *hdev,655struct hl_cs *cs,656struct hl_cs_compl *hl_cs_cmpl)657{658/* Skip this handler if the cs wasn't submitted, to avoid putting659* the hw_sob twice, since this case already handled at this point,660* also skip if the hw_sob pointer wasn't set.661*/662if (!hl_cs_cmpl->hw_sob || !cs->submitted)663return;664665spin_lock(&hl_cs_cmpl->lock);666667/*668* we get refcount upon reservation of signals or signal/wait cs for the669* hw_sob object, and need to put it when the first staged cs670* (which contains the encaps signals) or cs signal/wait is completed.671*/672if ((hl_cs_cmpl->type == CS_TYPE_SIGNAL) ||673(hl_cs_cmpl->type == CS_TYPE_WAIT) ||674(hl_cs_cmpl->type == CS_TYPE_COLLECTIVE_WAIT) ||675(!!hl_cs_cmpl->encaps_signals)) {676dev_dbg(hdev->dev,677"CS 0x%llx type %d finished, sob_id: %d, sob_val: %u\n",678hl_cs_cmpl->cs_seq,679hl_cs_cmpl->type,680hl_cs_cmpl->hw_sob->sob_id,681hl_cs_cmpl->sob_val);682683hw_sob_put(hl_cs_cmpl->hw_sob);684685if (hl_cs_cmpl->type == CS_TYPE_COLLECTIVE_WAIT)686hdev->asic_funcs->reset_sob_group(hdev,687hl_cs_cmpl->sob_group);688}689690spin_unlock(&hl_cs_cmpl->lock);691}692693static void cs_do_release(struct kref *ref)694{695struct hl_cs *cs = container_of(ref, struct hl_cs, refcount);696struct hl_device *hdev = cs->ctx->hdev;697struct hl_cs_job *job, *tmp;698struct hl_cs_compl *hl_cs_cmpl =699container_of(cs->fence, struct hl_cs_compl, base_fence);700701cs->completed = true;702703/*704* Although if we reached here it means that all external jobs have705* finished, because each one of them took refcnt to CS, we still706* need to go over the internal jobs and complete them. Otherwise, we707* will have leaked memory and what's worse, the CS object (and708* potentially the CTX object) could be released, while the JOB709* still holds a pointer to them (but no reference).710*/711list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)712hl_complete_job(hdev, job);713714if (!cs->submitted) {715/*716* In case the wait for signal CS was submitted, the fence put717* occurs in init_signal_wait_cs() or collective_wait_init_cs()718* right before hanging on the PQ.719*/720if (cs->type == CS_TYPE_WAIT ||721cs->type == CS_TYPE_COLLECTIVE_WAIT)722hl_fence_put(cs->signal_fence);723724goto out;725}726727/* Need to update CI for all queue jobs that does not get completion */728hl_hw_queue_update_ci(cs);729730/* remove CS from CS mirror list */731spin_lock(&hdev->cs_mirror_lock);732list_del_init(&cs->mirror_node);733spin_unlock(&hdev->cs_mirror_lock);734735cs_handle_tdr(hdev, cs);736737if (cs->staged_cs) {738/* the completion CS decrements reference for the entire739* staged submission740*/741if (cs->staged_last) {742struct hl_cs *staged_cs, *tmp_cs;743744list_for_each_entry_safe(staged_cs, tmp_cs,745&cs->staged_cs_node, staged_cs_node)746staged_cs_put(hdev, staged_cs);747}748749/* A staged CS will be a member in the list only after it750* was submitted. We used 'cs_mirror_lock' when inserting751* it to list so we will use it again when removing it752*/753if (cs->submitted) {754spin_lock(&hdev->cs_mirror_lock);755list_del(&cs->staged_cs_node);756spin_unlock(&hdev->cs_mirror_lock);757}758759/* decrement refcount to handle when first staged cs760* with encaps signals is completed.761*/762if (hl_cs_cmpl->encaps_signals)763kref_put(&hl_cs_cmpl->encaps_sig_hdl->refcount,764hl_encaps_release_handle_and_put_ctx);765}766767if ((cs->type == CS_TYPE_WAIT || cs->type == CS_TYPE_COLLECTIVE_WAIT) && cs->encaps_signals)768kref_put(&cs->encaps_sig_hdl->refcount, hl_encaps_release_handle_and_put_ctx);769770out:771/* Must be called before hl_ctx_put because inside we use ctx to get772* the device773*/774hl_debugfs_remove_cs(cs);775776hdev->shadow_cs_queue[cs->sequence & (hdev->asic_prop.max_pending_cs - 1)] = NULL;777778/* We need to mark an error for not submitted because in that case779* the hl fence release flow is different. Mainly, we don't need780* to handle hw_sob for signal/wait781*/782if (cs->timedout)783cs->fence->error = -ETIMEDOUT;784else if (cs->aborted)785cs->fence->error = -EIO;786else if (!cs->submitted)787cs->fence->error = -EBUSY;788789if (unlikely(cs->skip_reset_on_timeout)) {790dev_err(hdev->dev,791"Command submission %llu completed after %llu (s)\n",792cs->sequence,793div_u64(jiffies - cs->submission_time_jiffies, HZ));794}795796if (cs->timestamp) {797cs->fence->timestamp = cs->completion_timestamp;798hl_push_cs_outcome(hdev, &cs->ctx->outcome_store, cs->sequence,799cs->fence->timestamp, cs->fence->error);800}801802hl_ctx_put(cs->ctx);803804complete_all(&cs->fence->completion);805complete_multi_cs(hdev, cs);806807cs_release_sob_reset_handler(hdev, cs, hl_cs_cmpl);808809hl_fence_put(cs->fence);810811kfree(cs->jobs_in_queue_cnt);812kfree(cs);813}814815static void cs_timedout(struct work_struct *work)816{817struct hl_cs *cs = container_of(work, struct hl_cs, work_tdr.work);818bool skip_reset_on_timeout, device_reset = false;819struct hl_device *hdev;820u64 event_mask = 0x0;821uint timeout_sec;822int rc;823824skip_reset_on_timeout = cs->skip_reset_on_timeout;825826rc = cs_get_unless_zero(cs);827if (!rc)828return;829830if ((!cs->submitted) || (cs->completed)) {831cs_put(cs);832return;833}834835hdev = cs->ctx->hdev;836837if (likely(!skip_reset_on_timeout)) {838if (hdev->reset_on_lockup)839device_reset = true;840else841hdev->reset_info.needs_reset = true;842843/* Mark the CS is timed out so we won't try to cancel its TDR */844cs->timedout = true;845}846847/* Save only the first CS timeout parameters */848rc = atomic_cmpxchg(&hdev->captured_err_info.cs_timeout.write_enable, 1, 0);849if (rc) {850hdev->captured_err_info.cs_timeout.timestamp = ktime_get();851hdev->captured_err_info.cs_timeout.seq = cs->sequence;852event_mask |= HL_NOTIFIER_EVENT_CS_TIMEOUT;853}854855timeout_sec = jiffies_to_msecs(hdev->timeout_jiffies) / 1000;856857switch (cs->type) {858case CS_TYPE_SIGNAL:859dev_err(hdev->dev,860"Signal command submission %llu has not finished in %u seconds!\n",861cs->sequence, timeout_sec);862break;863864case CS_TYPE_WAIT:865dev_err(hdev->dev,866"Wait command submission %llu has not finished in %u seconds!\n",867cs->sequence, timeout_sec);868break;869870case CS_TYPE_COLLECTIVE_WAIT:871dev_err(hdev->dev,872"Collective Wait command submission %llu has not finished in %u seconds!\n",873cs->sequence, timeout_sec);874break;875876default:877dev_err(hdev->dev,878"Command submission %llu has not finished in %u seconds!\n",879cs->sequence, timeout_sec);880break;881}882883rc = hl_state_dump(hdev);884if (rc)885dev_err(hdev->dev, "Error during system state dump %d\n", rc);886887cs_put(cs);888889if (device_reset) {890event_mask |= HL_NOTIFIER_EVENT_DEVICE_RESET;891hl_device_cond_reset(hdev, HL_DRV_RESET_TDR, event_mask);892} else if (event_mask) {893hl_notifier_event_send_all(hdev, event_mask);894}895}896897static int allocate_cs(struct hl_device *hdev, struct hl_ctx *ctx,898enum hl_cs_type cs_type, u64 user_sequence,899struct hl_cs **cs_new, u32 flags, u32 timeout)900{901struct hl_cs_counters_atomic *cntr;902struct hl_fence *other = NULL;903struct hl_cs_compl *cs_cmpl;904struct hl_cs *cs;905int rc;906907cntr = &hdev->aggregated_cs_counters;908909cs = kzalloc(sizeof(*cs), GFP_ATOMIC);910if (!cs)911cs = kzalloc(sizeof(*cs), GFP_KERNEL);912913if (!cs) {914atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);915atomic64_inc(&cntr->out_of_mem_drop_cnt);916return -ENOMEM;917}918919/* increment refcnt for context */920hl_ctx_get(ctx);921922cs->ctx = ctx;923cs->submitted = false;924cs->completed = false;925cs->type = cs_type;926cs->timestamp = !!(flags & HL_CS_FLAGS_TIMESTAMP);927cs->encaps_signals = !!(flags & HL_CS_FLAGS_ENCAP_SIGNALS);928cs->timeout_jiffies = timeout;929cs->skip_reset_on_timeout =930hdev->reset_info.skip_reset_on_timeout ||931!!(flags & HL_CS_FLAGS_SKIP_RESET_ON_TIMEOUT);932cs->submission_time_jiffies = jiffies;933INIT_LIST_HEAD(&cs->job_list);934INIT_DELAYED_WORK(&cs->work_tdr, cs_timedout);935kref_init(&cs->refcount);936spin_lock_init(&cs->job_lock);937938cs_cmpl = kzalloc(sizeof(*cs_cmpl), GFP_ATOMIC);939if (!cs_cmpl)940cs_cmpl = kzalloc(sizeof(*cs_cmpl), GFP_KERNEL);941942if (!cs_cmpl) {943atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);944atomic64_inc(&cntr->out_of_mem_drop_cnt);945rc = -ENOMEM;946goto free_cs;947}948949cs->jobs_in_queue_cnt = kcalloc(hdev->asic_prop.max_queues,950sizeof(*cs->jobs_in_queue_cnt), GFP_ATOMIC);951if (!cs->jobs_in_queue_cnt)952cs->jobs_in_queue_cnt = kcalloc(hdev->asic_prop.max_queues,953sizeof(*cs->jobs_in_queue_cnt), GFP_KERNEL);954955if (!cs->jobs_in_queue_cnt) {956atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);957atomic64_inc(&cntr->out_of_mem_drop_cnt);958rc = -ENOMEM;959goto free_cs_cmpl;960}961962cs_cmpl->hdev = hdev;963cs_cmpl->type = cs->type;964spin_lock_init(&cs_cmpl->lock);965cs->fence = &cs_cmpl->base_fence;966967spin_lock(&ctx->cs_lock);968969cs_cmpl->cs_seq = ctx->cs_sequence;970other = ctx->cs_pending[cs_cmpl->cs_seq &971(hdev->asic_prop.max_pending_cs - 1)];972973if (other && !completion_done(&other->completion)) {974/* If the following statement is true, it means we have reached975* a point in which only part of the staged submission was976* submitted and we don't have enough room in the 'cs_pending'977* array for the rest of the submission.978* This causes a deadlock because this CS will never be979* completed as it depends on future CS's for completion.980*/981if (other->cs_sequence == user_sequence)982dev_crit_ratelimited(hdev->dev,983"Staged CS %llu deadlock due to lack of resources",984user_sequence);985986dev_dbg_ratelimited(hdev->dev,987"Rejecting CS because of too many in-flights CS\n");988atomic64_inc(&ctx->cs_counters.max_cs_in_flight_drop_cnt);989atomic64_inc(&cntr->max_cs_in_flight_drop_cnt);990rc = -EAGAIN;991goto free_fence;992}993994/* init hl_fence */995hl_fence_init(&cs_cmpl->base_fence, cs_cmpl->cs_seq);996997cs->sequence = cs_cmpl->cs_seq;998999ctx->cs_pending[cs_cmpl->cs_seq &1000(hdev->asic_prop.max_pending_cs - 1)] =1001&cs_cmpl->base_fence;1002ctx->cs_sequence++;10031004hl_fence_get(&cs_cmpl->base_fence);10051006hl_fence_put(other);10071008spin_unlock(&ctx->cs_lock);10091010*cs_new = cs;10111012return 0;10131014free_fence:1015spin_unlock(&ctx->cs_lock);1016kfree(cs->jobs_in_queue_cnt);1017free_cs_cmpl:1018kfree(cs_cmpl);1019free_cs:1020kfree(cs);1021hl_ctx_put(ctx);1022return rc;1023}10241025static void cs_rollback(struct hl_device *hdev, struct hl_cs *cs)1026{1027struct hl_cs_job *job, *tmp;10281029staged_cs_put(hdev, cs);10301031list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)1032hl_complete_job(hdev, job);1033}10341035/*1036* release_reserved_encaps_signals() - release reserved encapsulated signals.1037* @hdev: pointer to habanalabs device structure1038*1039* Release reserved encapsulated signals which weren't un-reserved, or for which a CS with1040* encapsulated signals wasn't submitted and thus weren't released as part of CS roll-back.1041* For these signals need also to put the refcount of the H/W SOB which was taken at the1042* reservation.1043*/1044static void release_reserved_encaps_signals(struct hl_device *hdev)1045{1046struct hl_ctx *ctx = hl_get_compute_ctx(hdev);1047struct hl_cs_encaps_sig_handle *handle;1048struct hl_encaps_signals_mgr *mgr;1049u32 id;10501051if (!ctx)1052return;10531054mgr = &ctx->sig_mgr;10551056idr_for_each_entry(&mgr->handles, handle, id)1057if (handle->cs_seq == ULLONG_MAX)1058kref_put(&handle->refcount, hl_encaps_release_handle_and_put_sob_ctx);10591060hl_ctx_put(ctx);1061}10621063void hl_cs_rollback_all(struct hl_device *hdev, bool skip_wq_flush)1064{1065int i;1066struct hl_cs *cs, *tmp;10671068if (!skip_wq_flush) {1069flush_workqueue(hdev->ts_free_obj_wq);10701071/* flush all completions before iterating over the CS mirror list in1072* order to avoid a race with the release functions1073*/1074for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)1075flush_workqueue(hdev->cq_wq[i]);10761077flush_workqueue(hdev->cs_cmplt_wq);1078}10791080/* Make sure we don't have leftovers in the CS mirror list */1081list_for_each_entry_safe(cs, tmp, &hdev->cs_mirror_list, mirror_node) {1082cs_get(cs);1083cs->aborted = true;1084dev_warn_ratelimited(hdev->dev, "Killing CS %d.%llu\n",1085cs->ctx->asid, cs->sequence);1086cs_rollback(hdev, cs);1087cs_put(cs);1088}10891090force_complete_multi_cs(hdev);10911092release_reserved_encaps_signals(hdev);1093}10941095static void1096wake_pending_user_interrupt_threads(struct hl_user_interrupt *interrupt)1097{1098struct hl_user_pending_interrupt *pend, *temp;1099unsigned long flags;11001101spin_lock_irqsave(&interrupt->wait_list_lock, flags);1102list_for_each_entry_safe(pend, temp, &interrupt->wait_list_head, list_node) {1103pend->fence.error = -EIO;1104complete_all(&pend->fence.completion);1105}1106spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);11071108spin_lock_irqsave(&interrupt->ts_list_lock, flags);1109list_for_each_entry_safe(pend, temp, &interrupt->ts_list_head, list_node) {1110list_del(&pend->list_node);1111hl_mmap_mem_buf_put(pend->ts_reg_info.buf);1112hl_cb_put(pend->ts_reg_info.cq_cb);1113}1114spin_unlock_irqrestore(&interrupt->ts_list_lock, flags);1115}11161117void hl_release_pending_user_interrupts(struct hl_device *hdev)1118{1119struct asic_fixed_properties *prop = &hdev->asic_prop;1120struct hl_user_interrupt *interrupt;1121int i;11221123if (!prop->user_interrupt_count)1124return;11251126/* We iterate through the user interrupt requests and waking up all1127* user threads waiting for interrupt completion. We iterate the1128* list under a lock, this is why all user threads, once awake,1129* will wait on the same lock and will release the waiting object upon1130* unlock.1131*/11321133for (i = 0 ; i < prop->user_interrupt_count ; i++) {1134interrupt = &hdev->user_interrupt[i];1135wake_pending_user_interrupt_threads(interrupt);1136}11371138interrupt = &hdev->common_user_cq_interrupt;1139wake_pending_user_interrupt_threads(interrupt);11401141interrupt = &hdev->common_decoder_interrupt;1142wake_pending_user_interrupt_threads(interrupt);1143}11441145static void force_complete_cs(struct hl_device *hdev)1146{1147struct hl_cs *cs;11481149spin_lock(&hdev->cs_mirror_lock);11501151list_for_each_entry(cs, &hdev->cs_mirror_list, mirror_node) {1152cs->fence->error = -EIO;1153complete_all(&cs->fence->completion);1154}11551156spin_unlock(&hdev->cs_mirror_lock);1157}11581159void hl_abort_waiting_for_cs_completions(struct hl_device *hdev)1160{1161force_complete_cs(hdev);1162force_complete_multi_cs(hdev);1163}11641165static void job_wq_completion(struct work_struct *work)1166{1167struct hl_cs_job *job = container_of(work, struct hl_cs_job,1168finish_work);1169struct hl_cs *cs = job->cs;1170struct hl_device *hdev = cs->ctx->hdev;11711172/* job is no longer needed */1173hl_complete_job(hdev, job);1174}11751176static void cs_completion(struct work_struct *work)1177{1178struct hl_cs *cs = container_of(work, struct hl_cs, finish_work);1179struct hl_device *hdev = cs->ctx->hdev;1180struct hl_cs_job *job, *tmp;11811182list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)1183hl_complete_job(hdev, job);1184}11851186u32 hl_get_active_cs_num(struct hl_device *hdev)1187{1188u32 active_cs_num = 0;1189struct hl_cs *cs;11901191spin_lock(&hdev->cs_mirror_lock);11921193list_for_each_entry(cs, &hdev->cs_mirror_list, mirror_node)1194if (!cs->completed)1195active_cs_num++;11961197spin_unlock(&hdev->cs_mirror_lock);11981199return active_cs_num;1200}12011202static int validate_queue_index(struct hl_device *hdev,1203struct hl_cs_chunk *chunk,1204enum hl_queue_type *queue_type,1205bool *is_kernel_allocated_cb)1206{1207struct asic_fixed_properties *asic = &hdev->asic_prop;1208struct hw_queue_properties *hw_queue_prop;12091210/* This must be checked here to prevent out-of-bounds access to1211* hw_queues_props array1212*/1213if (chunk->queue_index >= asic->max_queues) {1214dev_err(hdev->dev, "Queue index %d is invalid\n",1215chunk->queue_index);1216return -EINVAL;1217}12181219hw_queue_prop = &asic->hw_queues_props[chunk->queue_index];12201221if (hw_queue_prop->type == QUEUE_TYPE_NA) {1222dev_err(hdev->dev, "Queue index %d is not applicable\n",1223chunk->queue_index);1224return -EINVAL;1225}12261227if (hw_queue_prop->binned) {1228dev_err(hdev->dev, "Queue index %d is binned out\n",1229chunk->queue_index);1230return -EINVAL;1231}12321233if (hw_queue_prop->driver_only) {1234dev_err(hdev->dev,1235"Queue index %d is restricted for the kernel driver\n",1236chunk->queue_index);1237return -EINVAL;1238}12391240/* When hw queue type isn't QUEUE_TYPE_HW,1241* USER_ALLOC_CB flag shall be referred as "don't care".1242*/1243if (hw_queue_prop->type == QUEUE_TYPE_HW) {1244if (chunk->cs_chunk_flags & HL_CS_CHUNK_FLAGS_USER_ALLOC_CB) {1245if (!(hw_queue_prop->cb_alloc_flags & CB_ALLOC_USER)) {1246dev_err(hdev->dev,1247"Queue index %d doesn't support user CB\n",1248chunk->queue_index);1249return -EINVAL;1250}12511252*is_kernel_allocated_cb = false;1253} else {1254if (!(hw_queue_prop->cb_alloc_flags &1255CB_ALLOC_KERNEL)) {1256dev_err(hdev->dev,1257"Queue index %d doesn't support kernel CB\n",1258chunk->queue_index);1259return -EINVAL;1260}12611262*is_kernel_allocated_cb = true;1263}1264} else {1265*is_kernel_allocated_cb = !!(hw_queue_prop->cb_alloc_flags1266& CB_ALLOC_KERNEL);1267}12681269*queue_type = hw_queue_prop->type;1270return 0;1271}12721273static struct hl_cb *get_cb_from_cs_chunk(struct hl_device *hdev,1274struct hl_mem_mgr *mmg,1275struct hl_cs_chunk *chunk)1276{1277struct hl_cb *cb;12781279cb = hl_cb_get(mmg, chunk->cb_handle);1280if (!cb) {1281dev_err(hdev->dev, "CB handle 0x%llx invalid\n", chunk->cb_handle);1282return NULL;1283}12841285if ((chunk->cb_size < 8) || (chunk->cb_size > cb->size)) {1286dev_err(hdev->dev, "CB size %u invalid\n", chunk->cb_size);1287goto release_cb;1288}12891290atomic_inc(&cb->cs_cnt);12911292return cb;12931294release_cb:1295hl_cb_put(cb);1296return NULL;1297}12981299struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,1300enum hl_queue_type queue_type, bool is_kernel_allocated_cb)1301{1302struct hl_cs_job *job;13031304job = kzalloc(sizeof(*job), GFP_ATOMIC);1305if (!job)1306job = kzalloc(sizeof(*job), GFP_KERNEL);13071308if (!job)1309return NULL;13101311kref_init(&job->refcount);1312job->queue_type = queue_type;1313job->is_kernel_allocated_cb = is_kernel_allocated_cb;13141315if (is_cb_patched(hdev, job))1316INIT_LIST_HEAD(&job->userptr_list);13171318if (job->queue_type == QUEUE_TYPE_EXT)1319INIT_WORK(&job->finish_work, job_wq_completion);13201321return job;1322}13231324static enum hl_cs_type hl_cs_get_cs_type(u32 cs_type_flags)1325{1326if (cs_type_flags & HL_CS_FLAGS_SIGNAL)1327return CS_TYPE_SIGNAL;1328else if (cs_type_flags & HL_CS_FLAGS_WAIT)1329return CS_TYPE_WAIT;1330else if (cs_type_flags & HL_CS_FLAGS_COLLECTIVE_WAIT)1331return CS_TYPE_COLLECTIVE_WAIT;1332else if (cs_type_flags & HL_CS_FLAGS_RESERVE_SIGNALS_ONLY)1333return CS_RESERVE_SIGNALS;1334else if (cs_type_flags & HL_CS_FLAGS_UNRESERVE_SIGNALS_ONLY)1335return CS_UNRESERVE_SIGNALS;1336else if (cs_type_flags & HL_CS_FLAGS_ENGINE_CORE_COMMAND)1337return CS_TYPE_ENGINE_CORE;1338else if (cs_type_flags & HL_CS_FLAGS_ENGINES_COMMAND)1339return CS_TYPE_ENGINES;1340else if (cs_type_flags & HL_CS_FLAGS_FLUSH_PCI_HBW_WRITES)1341return CS_TYPE_FLUSH_PCI_HBW_WRITES;1342else1343return CS_TYPE_DEFAULT;1344}13451346static int hl_cs_sanity_checks(struct hl_fpriv *hpriv, union hl_cs_args *args)1347{1348struct hl_device *hdev = hpriv->hdev;1349struct hl_ctx *ctx = hpriv->ctx;1350u32 cs_type_flags, num_chunks;1351enum hl_device_status status;1352enum hl_cs_type cs_type;1353bool is_sync_stream;1354int i;13551356for (i = 0 ; i < sizeof(args->in.pad) ; i++)1357if (args->in.pad[i]) {1358dev_dbg(hdev->dev, "Padding bytes must be 0\n");1359return -EINVAL;1360}13611362if (!hl_device_operational(hdev, &status))1363return -EBUSY;13641365if ((args->in.cs_flags & HL_CS_FLAGS_STAGED_SUBMISSION) &&1366!hdev->supports_staged_submission) {1367dev_err(hdev->dev, "staged submission not supported");1368return -EPERM;1369}13701371cs_type_flags = args->in.cs_flags & HL_CS_FLAGS_TYPE_MASK;13721373if (unlikely(cs_type_flags && !is_power_of_2(cs_type_flags))) {1374dev_err(hdev->dev,1375"CS type flags are mutually exclusive, context %d\n",1376ctx->asid);1377return -EINVAL;1378}13791380cs_type = hl_cs_get_cs_type(cs_type_flags);1381num_chunks = args->in.num_chunks_execute;13821383is_sync_stream = (cs_type == CS_TYPE_SIGNAL || cs_type == CS_TYPE_WAIT ||1384cs_type == CS_TYPE_COLLECTIVE_WAIT);13851386if (unlikely(is_sync_stream && !hdev->supports_sync_stream)) {1387dev_err(hdev->dev, "Sync stream CS is not supported\n");1388return -EINVAL;1389}13901391if (cs_type == CS_TYPE_DEFAULT) {1392if (!num_chunks) {1393dev_err(hdev->dev, "Got execute CS with 0 chunks, context %d\n", ctx->asid);1394return -EINVAL;1395}1396} else if (is_sync_stream && num_chunks != 1) {1397dev_err(hdev->dev,1398"Sync stream CS mandates one chunk only, context %d\n",1399ctx->asid);1400return -EINVAL;1401}14021403return 0;1404}14051406static int hl_cs_copy_chunk_array(struct hl_device *hdev,1407struct hl_cs_chunk **cs_chunk_array,1408void __user *chunks, u32 num_chunks,1409struct hl_ctx *ctx)1410{1411u32 size_to_copy;14121413if (num_chunks > HL_MAX_JOBS_PER_CS) {1414atomic64_inc(&ctx->cs_counters.validation_drop_cnt);1415atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);1416dev_err(hdev->dev,1417"Number of chunks can NOT be larger than %d\n",1418HL_MAX_JOBS_PER_CS);1419return -EINVAL;1420}14211422*cs_chunk_array = kmalloc_array(num_chunks, sizeof(**cs_chunk_array),1423GFP_ATOMIC);1424if (!*cs_chunk_array)1425*cs_chunk_array = kmalloc_array(num_chunks,1426sizeof(**cs_chunk_array), GFP_KERNEL);1427if (!*cs_chunk_array) {1428atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);1429atomic64_inc(&hdev->aggregated_cs_counters.out_of_mem_drop_cnt);1430return -ENOMEM;1431}14321433size_to_copy = num_chunks * sizeof(struct hl_cs_chunk);1434if (copy_from_user(*cs_chunk_array, chunks, size_to_copy)) {1435atomic64_inc(&ctx->cs_counters.validation_drop_cnt);1436atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);1437dev_err(hdev->dev, "Failed to copy cs chunk array from user\n");1438kfree(*cs_chunk_array);1439return -EFAULT;1440}14411442return 0;1443}14441445static int cs_staged_submission(struct hl_device *hdev, struct hl_cs *cs,1446u64 sequence, u32 flags,1447u32 encaps_signal_handle)1448{1449if (!(flags & HL_CS_FLAGS_STAGED_SUBMISSION))1450return 0;14511452cs->staged_last = !!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_LAST);1453cs->staged_first = !!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_FIRST);14541455if (cs->staged_first) {1456/* Staged CS sequence is the first CS sequence */1457INIT_LIST_HEAD(&cs->staged_cs_node);1458cs->staged_sequence = cs->sequence;14591460if (cs->encaps_signals)1461cs->encaps_sig_hdl_id = encaps_signal_handle;1462} else {1463/* User sequence will be validated in 'hl_hw_queue_schedule_cs'1464* under the cs_mirror_lock1465*/1466cs->staged_sequence = sequence;1467}14681469/* Increment CS reference if needed */1470staged_cs_get(hdev, cs);14711472cs->staged_cs = true;14731474return 0;1475}14761477static u32 get_stream_master_qid_mask(struct hl_device *hdev, u32 qid)1478{1479int i;14801481for (i = 0; i < hdev->stream_master_qid_arr_size; i++)1482if (qid == hdev->stream_master_qid_arr[i])1483return BIT(i);14841485return 0;1486}14871488static int cs_ioctl_default(struct hl_fpriv *hpriv, void __user *chunks,1489u32 num_chunks, u64 *cs_seq, u32 flags,1490u32 encaps_signals_handle, u32 timeout,1491u16 *signal_initial_sob_count)1492{1493bool staged_mid, int_queues_only = true, using_hw_queues = false;1494struct hl_device *hdev = hpriv->hdev;1495struct hl_cs_chunk *cs_chunk_array;1496struct hl_cs_counters_atomic *cntr;1497struct hl_ctx *ctx = hpriv->ctx;1498struct hl_cs_job *job;1499struct hl_cs *cs;1500struct hl_cb *cb;1501u64 user_sequence;1502u8 stream_master_qid_map = 0;1503int rc, i;15041505cntr = &hdev->aggregated_cs_counters;1506user_sequence = *cs_seq;1507*cs_seq = ULLONG_MAX;15081509rc = hl_cs_copy_chunk_array(hdev, &cs_chunk_array, chunks, num_chunks,1510hpriv->ctx);1511if (rc)1512goto out;15131514if ((flags & HL_CS_FLAGS_STAGED_SUBMISSION) &&1515!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_FIRST))1516staged_mid = true;1517else1518staged_mid = false;15191520rc = allocate_cs(hdev, hpriv->ctx, CS_TYPE_DEFAULT,1521staged_mid ? user_sequence : ULLONG_MAX, &cs, flags,1522timeout);1523if (rc)1524goto free_cs_chunk_array;15251526*cs_seq = cs->sequence;15271528hl_debugfs_add_cs(cs);15291530rc = cs_staged_submission(hdev, cs, user_sequence, flags,1531encaps_signals_handle);1532if (rc)1533goto free_cs_object;15341535/* If this is a staged submission we must return the staged sequence1536* rather than the internal CS sequence1537*/1538if (cs->staged_cs)1539*cs_seq = cs->staged_sequence;15401541/* Validate ALL the CS chunks before submitting the CS */1542for (i = 0 ; i < num_chunks ; i++) {1543struct hl_cs_chunk *chunk = &cs_chunk_array[i];1544enum hl_queue_type queue_type;1545bool is_kernel_allocated_cb;15461547rc = validate_queue_index(hdev, chunk, &queue_type,1548&is_kernel_allocated_cb);1549if (rc) {1550atomic64_inc(&ctx->cs_counters.validation_drop_cnt);1551atomic64_inc(&cntr->validation_drop_cnt);1552goto free_cs_object;1553}15541555if (is_kernel_allocated_cb) {1556cb = get_cb_from_cs_chunk(hdev, &hpriv->mem_mgr, chunk);1557if (!cb) {1558atomic64_inc(1559&ctx->cs_counters.validation_drop_cnt);1560atomic64_inc(&cntr->validation_drop_cnt);1561rc = -EINVAL;1562goto free_cs_object;1563}1564} else {1565cb = (struct hl_cb *) (uintptr_t) chunk->cb_handle;1566}15671568if (queue_type == QUEUE_TYPE_EXT ||1569queue_type == QUEUE_TYPE_HW) {1570int_queues_only = false;15711572/*1573* store which stream are being used for external/HW1574* queues of this CS1575*/1576if (hdev->supports_wait_for_multi_cs)1577stream_master_qid_map |=1578get_stream_master_qid_mask(hdev,1579chunk->queue_index);1580}15811582if (queue_type == QUEUE_TYPE_HW)1583using_hw_queues = true;15841585job = hl_cs_allocate_job(hdev, queue_type,1586is_kernel_allocated_cb);1587if (!job) {1588atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);1589atomic64_inc(&cntr->out_of_mem_drop_cnt);1590dev_err(hdev->dev, "Failed to allocate a new job\n");1591rc = -ENOMEM;1592if (is_kernel_allocated_cb)1593goto release_cb;15941595goto free_cs_object;1596}15971598job->id = i + 1;1599job->cs = cs;1600job->user_cb = cb;1601job->user_cb_size = chunk->cb_size;1602job->hw_queue_id = chunk->queue_index;16031604cs->jobs_in_queue_cnt[job->hw_queue_id]++;1605cs->jobs_cnt++;16061607list_add_tail(&job->cs_node, &cs->job_list);16081609/*1610* Increment CS reference. When CS reference is 0, CS is1611* done and can be signaled to user and free all its resources1612* Only increment for JOB on external or H/W queues, because1613* only for those JOBs we get completion1614*/1615if (cs_needs_completion(cs) &&1616(job->queue_type == QUEUE_TYPE_EXT ||1617job->queue_type == QUEUE_TYPE_HW))1618cs_get(cs);16191620hl_debugfs_add_job(hdev, job);16211622rc = cs_parser(hpriv, job);1623if (rc) {1624atomic64_inc(&ctx->cs_counters.parsing_drop_cnt);1625atomic64_inc(&cntr->parsing_drop_cnt);1626dev_err(hdev->dev,1627"Failed to parse JOB %d.%llu.%d, err %d, rejecting the CS\n",1628cs->ctx->asid, cs->sequence, job->id, rc);1629goto free_cs_object;1630}1631}16321633/* We allow a CS with any queue type combination as long as it does1634* not get a completion1635*/1636if (int_queues_only && cs_needs_completion(cs)) {1637atomic64_inc(&ctx->cs_counters.validation_drop_cnt);1638atomic64_inc(&cntr->validation_drop_cnt);1639dev_err(hdev->dev,1640"Reject CS %d.%llu since it contains only internal queues jobs and needs completion\n",1641cs->ctx->asid, cs->sequence);1642rc = -EINVAL;1643goto free_cs_object;1644}16451646if (using_hw_queues)1647INIT_WORK(&cs->finish_work, cs_completion);16481649/*1650* store the (external/HW queues) streams used by the CS in the1651* fence object for multi-CS completion1652*/1653if (hdev->supports_wait_for_multi_cs)1654cs->fence->stream_master_qid_map = stream_master_qid_map;16551656rc = hl_hw_queue_schedule_cs(cs);1657if (rc) {1658if (rc != -EAGAIN)1659dev_err(hdev->dev,1660"Failed to submit CS %d.%llu to H/W queues, error %d\n",1661cs->ctx->asid, cs->sequence, rc);1662goto free_cs_object;1663}16641665*signal_initial_sob_count = cs->initial_sob_count;16661667rc = HL_CS_STATUS_SUCCESS;1668goto put_cs;16691670release_cb:1671atomic_dec(&cb->cs_cnt);1672hl_cb_put(cb);1673free_cs_object:1674cs_rollback(hdev, cs);1675*cs_seq = ULLONG_MAX;1676/* The path below is both for good and erroneous exits */1677put_cs:1678/* We finished with the CS in this function, so put the ref */1679cs_put(cs);1680free_cs_chunk_array:1681kfree(cs_chunk_array);1682out:1683return rc;1684}16851686static int hl_cs_ctx_switch(struct hl_fpriv *hpriv, union hl_cs_args *args,1687u64 *cs_seq)1688{1689struct hl_device *hdev = hpriv->hdev;1690struct hl_ctx *ctx = hpriv->ctx;1691bool need_soft_reset = false;1692int rc = 0, do_ctx_switch = 0;1693void __user *chunks;1694u32 num_chunks, tmp;1695u16 sob_count;1696int ret;16971698if (hdev->supports_ctx_switch)1699do_ctx_switch = atomic_cmpxchg(&ctx->thread_ctx_switch_token, 1, 0);17001701if (do_ctx_switch || (args->in.cs_flags & HL_CS_FLAGS_FORCE_RESTORE)) {1702mutex_lock(&hpriv->restore_phase_mutex);17031704if (do_ctx_switch) {1705rc = hdev->asic_funcs->context_switch(hdev, ctx->asid);1706if (rc) {1707dev_err_ratelimited(hdev->dev,1708"Failed to switch to context %d, rejecting CS! %d\n",1709ctx->asid, rc);1710/*1711* If we timedout, or if the device is not IDLE1712* while we want to do context-switch (-EBUSY),1713* we need to soft-reset because QMAN is1714* probably stuck. However, we can't call to1715* reset here directly because of deadlock, so1716* need to do it at the very end of this1717* function1718*/1719if ((rc == -ETIMEDOUT) || (rc == -EBUSY))1720need_soft_reset = true;1721mutex_unlock(&hpriv->restore_phase_mutex);1722goto out;1723}1724}17251726hdev->asic_funcs->restore_phase_topology(hdev);17271728chunks = (void __user *) (uintptr_t) args->in.chunks_restore;1729num_chunks = args->in.num_chunks_restore;17301731if (!num_chunks) {1732dev_dbg(hdev->dev,1733"Need to run restore phase but restore CS is empty\n");1734rc = 0;1735} else {1736rc = cs_ioctl_default(hpriv, chunks, num_chunks,1737cs_seq, 0, 0, hdev->timeout_jiffies, &sob_count);1738}17391740mutex_unlock(&hpriv->restore_phase_mutex);17411742if (rc) {1743dev_err(hdev->dev,1744"Failed to submit restore CS for context %d (%d)\n",1745ctx->asid, rc);1746goto out;1747}17481749/* Need to wait for restore completion before execution phase */1750if (num_chunks) {1751enum hl_cs_wait_status status;17521753ret = _hl_cs_wait_ioctl(hdev, ctx,1754jiffies_to_usecs(hdev->timeout_jiffies),1755*cs_seq, &status, NULL);1756if (ret) {1757dev_err(hdev->dev,1758"Restore CS for context %d failed to complete %d\n",1759ctx->asid, ret);1760rc = -ENOEXEC;1761goto out;1762}1763}17641765if (hdev->supports_ctx_switch)1766ctx->thread_ctx_switch_wait_token = 1;17671768} else if (hdev->supports_ctx_switch && !ctx->thread_ctx_switch_wait_token) {1769rc = hl_poll_timeout_memory(hdev,1770&ctx->thread_ctx_switch_wait_token, tmp, (tmp == 1),1771100, jiffies_to_usecs(hdev->timeout_jiffies), false);17721773if (rc == -ETIMEDOUT) {1774dev_err(hdev->dev,1775"context switch phase timeout (%d)\n", tmp);1776goto out;1777}1778}17791780out:1781if ((rc == -ETIMEDOUT || rc == -EBUSY) && (need_soft_reset))1782hl_device_reset(hdev, 0);17831784return rc;1785}17861787/*1788* hl_cs_signal_sob_wraparound_handler: handle SOB value wrapaound case.1789* if the SOB value reaches the max value move to the other SOB reserved1790* to the queue.1791* @hdev: pointer to device structure1792* @q_idx: stream queue index1793* @hw_sob: the H/W SOB used in this signal CS.1794* @count: signals count1795* @encaps_sig: tells whether it's reservation for encaps signals or not.1796*1797* Note that this function must be called while hw_queues_lock is taken.1798*/1799int hl_cs_signal_sob_wraparound_handler(struct hl_device *hdev, u32 q_idx,1800struct hl_hw_sob **hw_sob, u32 count, bool encaps_sig)18011802{1803struct hl_sync_stream_properties *prop;1804struct hl_hw_sob *sob = *hw_sob, *other_sob;1805u8 other_sob_offset;18061807prop = &hdev->kernel_queues[q_idx].sync_stream_prop;18081809hw_sob_get(sob);18101811/* check for wraparound */1812if (prop->next_sob_val + count >= HL_MAX_SOB_VAL) {1813/*1814* Decrement as we reached the max value.1815* The release function won't be called here as we've1816* just incremented the refcount right before calling this1817* function.1818*/1819hw_sob_put_err(sob);18201821/*1822* check the other sob value, if it still in use then fail1823* otherwise make the switch1824*/1825other_sob_offset = (prop->curr_sob_offset + 1) % HL_RSVD_SOBS;1826other_sob = &prop->hw_sob[other_sob_offset];18271828if (kref_read(&other_sob->kref) != 1) {1829dev_err(hdev->dev, "error: Cannot switch SOBs q_idx: %d\n",1830q_idx);1831return -EINVAL;1832}18331834/*1835* next_sob_val always points to the next available signal1836* in the sob, so in encaps signals it will be the next one1837* after reserving the required amount.1838*/1839if (encaps_sig)1840prop->next_sob_val = count + 1;1841else1842prop->next_sob_val = count;18431844/* only two SOBs are currently in use */1845prop->curr_sob_offset = other_sob_offset;1846*hw_sob = other_sob;18471848/*1849* check if other_sob needs reset, then do it before using it1850* for the reservation or the next signal cs.1851* we do it here, and for both encaps and regular signal cs1852* cases in order to avoid possible races of two kref_put1853* of the sob which can occur at the same time if we move the1854* sob reset(kref_put) to cs_do_release function.1855* in addition, if we have combination of cs signal and1856* encaps, and at the point we need to reset the sob there was1857* no more reservations and only signal cs keep coming,1858* in such case we need signal_cs to put the refcount and1859* reset the sob.1860*/1861if (other_sob->need_reset)1862hw_sob_put(other_sob);18631864if (encaps_sig) {1865/* set reset indication for the sob */1866sob->need_reset = true;1867hw_sob_get(other_sob);1868}18691870dev_dbg(hdev->dev, "switched to SOB %d, q_idx: %d\n",1871prop->curr_sob_offset, q_idx);1872} else {1873prop->next_sob_val += count;1874}18751876return 0;1877}18781879static int cs_ioctl_extract_signal_seq(struct hl_device *hdev,1880struct hl_cs_chunk *chunk, u64 *signal_seq, struct hl_ctx *ctx,1881bool encaps_signals)1882{1883u64 *signal_seq_arr = NULL;1884u32 size_to_copy, signal_seq_arr_len;1885int rc = 0;18861887if (encaps_signals) {1888*signal_seq = chunk->encaps_signal_seq;1889return 0;1890}18911892signal_seq_arr_len = chunk->num_signal_seq_arr;18931894/* currently only one signal seq is supported */1895if (signal_seq_arr_len != 1) {1896atomic64_inc(&ctx->cs_counters.validation_drop_cnt);1897atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);1898dev_err(hdev->dev,1899"Wait for signal CS supports only one signal CS seq\n");1900return -EINVAL;1901}19021903signal_seq_arr = kmalloc_array(signal_seq_arr_len,1904sizeof(*signal_seq_arr),1905GFP_ATOMIC);1906if (!signal_seq_arr)1907signal_seq_arr = kmalloc_array(signal_seq_arr_len,1908sizeof(*signal_seq_arr),1909GFP_KERNEL);1910if (!signal_seq_arr) {1911atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);1912atomic64_inc(&hdev->aggregated_cs_counters.out_of_mem_drop_cnt);1913return -ENOMEM;1914}19151916size_to_copy = signal_seq_arr_len * sizeof(*signal_seq_arr);1917if (copy_from_user(signal_seq_arr,1918u64_to_user_ptr(chunk->signal_seq_arr),1919size_to_copy)) {1920atomic64_inc(&ctx->cs_counters.validation_drop_cnt);1921atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);1922dev_err(hdev->dev,1923"Failed to copy signal seq array from user\n");1924rc = -EFAULT;1925goto out;1926}19271928/* currently it is guaranteed to have only one signal seq */1929*signal_seq = signal_seq_arr[0];19301931out:1932kfree(signal_seq_arr);19331934return rc;1935}19361937static int cs_ioctl_signal_wait_create_jobs(struct hl_device *hdev,1938struct hl_ctx *ctx, struct hl_cs *cs,1939enum hl_queue_type q_type, u32 q_idx, u32 encaps_signal_offset)1940{1941struct hl_cs_counters_atomic *cntr;1942struct hl_cs_job *job;1943struct hl_cb *cb;1944u32 cb_size;19451946cntr = &hdev->aggregated_cs_counters;19471948job = hl_cs_allocate_job(hdev, q_type, true);1949if (!job) {1950atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);1951atomic64_inc(&cntr->out_of_mem_drop_cnt);1952dev_err(hdev->dev, "Failed to allocate a new job\n");1953return -ENOMEM;1954}19551956if (cs->type == CS_TYPE_WAIT)1957cb_size = hdev->asic_funcs->get_wait_cb_size(hdev);1958else1959cb_size = hdev->asic_funcs->get_signal_cb_size(hdev);19601961cb = hl_cb_kernel_create(hdev, cb_size, q_type == QUEUE_TYPE_HW);1962if (!cb) {1963atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);1964atomic64_inc(&cntr->out_of_mem_drop_cnt);1965kfree(job);1966return -EFAULT;1967}19681969job->id = 0;1970job->cs = cs;1971job->user_cb = cb;1972atomic_inc(&job->user_cb->cs_cnt);1973job->user_cb_size = cb_size;1974job->hw_queue_id = q_idx;19751976if ((cs->type == CS_TYPE_WAIT || cs->type == CS_TYPE_COLLECTIVE_WAIT)1977&& cs->encaps_signals)1978job->encaps_sig_wait_offset = encaps_signal_offset;1979/*1980* No need in parsing, user CB is the patched CB.1981* We call hl_cb_destroy() out of two reasons - we don't need the CB in1982* the CB idr anymore and to decrement its refcount as it was1983* incremented inside hl_cb_kernel_create().1984*/1985job->patched_cb = job->user_cb;1986job->job_cb_size = job->user_cb_size;1987hl_cb_destroy(&hdev->kernel_mem_mgr, cb->buf->handle);19881989/* increment refcount as for external queues we get completion */1990cs_get(cs);19911992cs->jobs_in_queue_cnt[job->hw_queue_id]++;1993cs->jobs_cnt++;19941995list_add_tail(&job->cs_node, &cs->job_list);19961997hl_debugfs_add_job(hdev, job);19981999return 0;2000}20012002static int cs_ioctl_reserve_signals(struct hl_fpriv *hpriv,2003u32 q_idx, u32 count,2004u32 *handle_id, u32 *sob_addr,2005u32 *signals_count)2006{2007struct hw_queue_properties *hw_queue_prop;2008struct hl_sync_stream_properties *prop;2009struct hl_device *hdev = hpriv->hdev;2010struct hl_cs_encaps_sig_handle *handle;2011struct hl_encaps_signals_mgr *mgr;2012struct hl_hw_sob *hw_sob;2013int hdl_id;2014int rc = 0;20152016if (count >= HL_MAX_SOB_VAL) {2017dev_err(hdev->dev, "signals count(%u) exceeds the max SOB value\n",2018count);2019rc = -EINVAL;2020goto out;2021}20222023if (q_idx >= hdev->asic_prop.max_queues) {2024dev_err(hdev->dev, "Queue index %d is invalid\n",2025q_idx);2026rc = -EINVAL;2027goto out;2028}20292030hw_queue_prop = &hdev->asic_prop.hw_queues_props[q_idx];20312032if (!hw_queue_prop->supports_sync_stream) {2033dev_err(hdev->dev,2034"Queue index %d does not support sync stream operations\n",2035q_idx);2036rc = -EINVAL;2037goto out;2038}20392040prop = &hdev->kernel_queues[q_idx].sync_stream_prop;20412042handle = kzalloc(sizeof(*handle), GFP_KERNEL);2043if (!handle) {2044rc = -ENOMEM;2045goto out;2046}20472048handle->count = count;20492050hl_ctx_get(hpriv->ctx);2051handle->ctx = hpriv->ctx;2052mgr = &hpriv->ctx->sig_mgr;20532054spin_lock(&mgr->lock);2055hdl_id = idr_alloc(&mgr->handles, handle, 1, 0, GFP_ATOMIC);2056spin_unlock(&mgr->lock);20572058if (hdl_id < 0) {2059dev_err(hdev->dev, "Failed to allocate IDR for a new signal reservation\n");2060rc = -EINVAL;2061goto put_ctx;2062}20632064handle->id = hdl_id;2065handle->q_idx = q_idx;2066handle->hdev = hdev;2067kref_init(&handle->refcount);20682069hdev->asic_funcs->hw_queues_lock(hdev);20702071hw_sob = &prop->hw_sob[prop->curr_sob_offset];20722073/*2074* Increment the SOB value by count by user request2075* to reserve those signals2076* check if the signals amount to reserve is not exceeding the max sob2077* value, if yes then switch sob.2078*/2079rc = hl_cs_signal_sob_wraparound_handler(hdev, q_idx, &hw_sob, count,2080true);2081if (rc) {2082dev_err(hdev->dev, "Failed to switch SOB\n");2083hdev->asic_funcs->hw_queues_unlock(hdev);2084rc = -EINVAL;2085goto remove_idr;2086}2087/* set the hw_sob to the handle after calling the sob wraparound handler2088* since sob could have changed.2089*/2090handle->hw_sob = hw_sob;20912092/* store the current sob value for unreserve validity check, and2093* signal offset support2094*/2095handle->pre_sob_val = prop->next_sob_val - handle->count;20962097handle->cs_seq = ULLONG_MAX;20982099*signals_count = prop->next_sob_val;2100hdev->asic_funcs->hw_queues_unlock(hdev);21012102*sob_addr = handle->hw_sob->sob_addr;2103*handle_id = hdl_id;21042105dev_dbg(hdev->dev,2106"Signals reserved, sob_id: %d, sob addr: 0x%x, last sob_val: %u, q_idx: %d, hdl_id: %d\n",2107hw_sob->sob_id, handle->hw_sob->sob_addr,2108prop->next_sob_val - 1, q_idx, hdl_id);2109goto out;21102111remove_idr:2112spin_lock(&mgr->lock);2113idr_remove(&mgr->handles, hdl_id);2114spin_unlock(&mgr->lock);21152116put_ctx:2117hl_ctx_put(handle->ctx);2118kfree(handle);21192120out:2121return rc;2122}21232124static int cs_ioctl_unreserve_signals(struct hl_fpriv *hpriv, u32 handle_id)2125{2126struct hl_cs_encaps_sig_handle *encaps_sig_hdl;2127struct hl_sync_stream_properties *prop;2128struct hl_device *hdev = hpriv->hdev;2129struct hl_encaps_signals_mgr *mgr;2130struct hl_hw_sob *hw_sob;2131u32 q_idx, sob_addr;2132int rc = 0;21332134mgr = &hpriv->ctx->sig_mgr;21352136spin_lock(&mgr->lock);2137encaps_sig_hdl = idr_find(&mgr->handles, handle_id);2138if (encaps_sig_hdl) {2139dev_dbg(hdev->dev, "unreserve signals, handle: %u, SOB:0x%x, count: %u\n",2140handle_id, encaps_sig_hdl->hw_sob->sob_addr,2141encaps_sig_hdl->count);21422143hdev->asic_funcs->hw_queues_lock(hdev);21442145q_idx = encaps_sig_hdl->q_idx;2146prop = &hdev->kernel_queues[q_idx].sync_stream_prop;2147hw_sob = &prop->hw_sob[prop->curr_sob_offset];2148sob_addr = hdev->asic_funcs->get_sob_addr(hdev, hw_sob->sob_id);21492150/* Check if sob_val got out of sync due to other2151* signal submission requests which were handled2152* between the reserve-unreserve calls or SOB switch2153* upon reaching SOB max value.2154*/2155if (encaps_sig_hdl->pre_sob_val + encaps_sig_hdl->count2156!= prop->next_sob_val ||2157sob_addr != encaps_sig_hdl->hw_sob->sob_addr) {2158dev_err(hdev->dev, "Cannot unreserve signals, SOB val ran out of sync, expected: %u, actual val: %u\n",2159encaps_sig_hdl->pre_sob_val,2160(prop->next_sob_val - encaps_sig_hdl->count));21612162hdev->asic_funcs->hw_queues_unlock(hdev);2163rc = -EINVAL;2164goto out_unlock;2165}21662167/*2168* Decrement the SOB value by count by user request2169* to unreserve those signals2170*/2171prop->next_sob_val -= encaps_sig_hdl->count;21722173hdev->asic_funcs->hw_queues_unlock(hdev);21742175hw_sob_put(hw_sob);21762177/* Release the id and free allocated memory of the handle */2178idr_remove(&mgr->handles, handle_id);21792180/* unlock before calling ctx_put, where we might sleep */2181spin_unlock(&mgr->lock);2182hl_ctx_put(encaps_sig_hdl->ctx);2183kfree(encaps_sig_hdl);2184goto out;2185} else {2186rc = -EINVAL;2187dev_err(hdev->dev, "failed to unreserve signals, cannot find handler\n");2188}21892190out_unlock:2191spin_unlock(&mgr->lock);21922193out:2194return rc;2195}21962197static int cs_ioctl_signal_wait(struct hl_fpriv *hpriv, enum hl_cs_type cs_type,2198void __user *chunks, u32 num_chunks,2199u64 *cs_seq, u32 flags, u32 timeout,2200u32 *signal_sob_addr_offset, u16 *signal_initial_sob_count)2201{2202struct hl_cs_encaps_sig_handle *encaps_sig_hdl = NULL;2203bool handle_found = false, is_wait_cs = false,2204wait_cs_submitted = false,2205cs_encaps_signals = false;2206struct hl_cs_chunk *cs_chunk_array, *chunk;2207bool staged_cs_with_encaps_signals = false;2208struct hw_queue_properties *hw_queue_prop;2209struct hl_device *hdev = hpriv->hdev;2210struct hl_cs_compl *sig_waitcs_cmpl;2211u32 q_idx, collective_engine_id = 0;2212struct hl_cs_counters_atomic *cntr;2213struct hl_fence *sig_fence = NULL;2214struct hl_ctx *ctx = hpriv->ctx;2215enum hl_queue_type q_type;2216struct hl_cs *cs;2217u64 signal_seq;2218int rc;22192220cntr = &hdev->aggregated_cs_counters;2221*cs_seq = ULLONG_MAX;22222223rc = hl_cs_copy_chunk_array(hdev, &cs_chunk_array, chunks, num_chunks,2224ctx);2225if (rc)2226goto out;22272228/* currently it is guaranteed to have only one chunk */2229chunk = &cs_chunk_array[0];22302231if (chunk->queue_index >= hdev->asic_prop.max_queues) {2232atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2233atomic64_inc(&cntr->validation_drop_cnt);2234dev_err(hdev->dev, "Queue index %d is invalid\n",2235chunk->queue_index);2236rc = -EINVAL;2237goto free_cs_chunk_array;2238}22392240q_idx = chunk->queue_index;2241hw_queue_prop = &hdev->asic_prop.hw_queues_props[q_idx];2242q_type = hw_queue_prop->type;22432244if (!hw_queue_prop->supports_sync_stream) {2245atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2246atomic64_inc(&cntr->validation_drop_cnt);2247dev_err(hdev->dev,2248"Queue index %d does not support sync stream operations\n",2249q_idx);2250rc = -EINVAL;2251goto free_cs_chunk_array;2252}22532254if (cs_type == CS_TYPE_COLLECTIVE_WAIT) {2255if (!(hw_queue_prop->collective_mode == HL_COLLECTIVE_MASTER)) {2256atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2257atomic64_inc(&cntr->validation_drop_cnt);2258dev_err(hdev->dev,2259"Queue index %d is invalid\n", q_idx);2260rc = -EINVAL;2261goto free_cs_chunk_array;2262}22632264if (!hdev->nic_ports_mask) {2265atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2266atomic64_inc(&cntr->validation_drop_cnt);2267dev_err(hdev->dev,2268"Collective operations not supported when NIC ports are disabled");2269rc = -EINVAL;2270goto free_cs_chunk_array;2271}22722273collective_engine_id = chunk->collective_engine_id;2274}22752276is_wait_cs = !!(cs_type == CS_TYPE_WAIT ||2277cs_type == CS_TYPE_COLLECTIVE_WAIT);22782279cs_encaps_signals = !!(flags & HL_CS_FLAGS_ENCAP_SIGNALS);22802281if (is_wait_cs) {2282rc = cs_ioctl_extract_signal_seq(hdev, chunk, &signal_seq,2283ctx, cs_encaps_signals);2284if (rc)2285goto free_cs_chunk_array;22862287if (cs_encaps_signals) {2288/* check if cs sequence has encapsulated2289* signals handle2290*/2291struct idr *idp;2292u32 id;22932294spin_lock(&ctx->sig_mgr.lock);2295idp = &ctx->sig_mgr.handles;2296idr_for_each_entry(idp, encaps_sig_hdl, id) {2297if (encaps_sig_hdl->cs_seq == signal_seq) {2298/* get refcount to protect removing this handle from idr,2299* needed when multiple wait cs are used with offset2300* to wait on reserved encaps signals.2301* Since kref_put of this handle is executed outside the2302* current lock, it is possible that the handle refcount2303* is 0 but it yet to be removed from the list. In this2304* case need to consider the handle as not valid.2305*/2306if (kref_get_unless_zero(&encaps_sig_hdl->refcount))2307handle_found = true;2308break;2309}2310}2311spin_unlock(&ctx->sig_mgr.lock);23122313if (!handle_found) {2314/* treat as signal CS already finished */2315dev_dbg(hdev->dev, "Cannot find encapsulated signals handle for seq 0x%llx\n",2316signal_seq);2317rc = 0;2318goto free_cs_chunk_array;2319}23202321/* validate also the signal offset value */2322if (chunk->encaps_signal_offset >2323encaps_sig_hdl->count) {2324dev_err(hdev->dev, "offset(%u) value exceed max reserved signals count(%u)!\n",2325chunk->encaps_signal_offset,2326encaps_sig_hdl->count);2327rc = -EINVAL;2328goto free_cs_chunk_array;2329}2330}23312332sig_fence = hl_ctx_get_fence(ctx, signal_seq);2333if (IS_ERR(sig_fence)) {2334atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2335atomic64_inc(&cntr->validation_drop_cnt);2336dev_err(hdev->dev,2337"Failed to get signal CS with seq 0x%llx\n",2338signal_seq);2339rc = PTR_ERR(sig_fence);2340goto free_cs_chunk_array;2341}23422343if (!sig_fence) {2344/* signal CS already finished */2345rc = 0;2346goto free_cs_chunk_array;2347}23482349sig_waitcs_cmpl =2350container_of(sig_fence, struct hl_cs_compl, base_fence);23512352staged_cs_with_encaps_signals = !!2353(sig_waitcs_cmpl->type == CS_TYPE_DEFAULT &&2354(flags & HL_CS_FLAGS_ENCAP_SIGNALS));23552356if (sig_waitcs_cmpl->type != CS_TYPE_SIGNAL &&2357!staged_cs_with_encaps_signals) {2358atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2359atomic64_inc(&cntr->validation_drop_cnt);2360dev_err(hdev->dev,2361"CS seq 0x%llx is not of a signal/encaps-signal CS\n",2362signal_seq);2363hl_fence_put(sig_fence);2364rc = -EINVAL;2365goto free_cs_chunk_array;2366}23672368if (completion_done(&sig_fence->completion)) {2369/* signal CS already finished */2370hl_fence_put(sig_fence);2371rc = 0;2372goto free_cs_chunk_array;2373}2374}23752376rc = allocate_cs(hdev, ctx, cs_type, ULLONG_MAX, &cs, flags, timeout);2377if (rc) {2378if (is_wait_cs)2379hl_fence_put(sig_fence);23802381goto free_cs_chunk_array;2382}23832384/*2385* Save the signal CS fence for later initialization right before2386* hanging the wait CS on the queue.2387* for encaps signals case, we save the cs sequence and handle pointer2388* for later initialization.2389*/2390if (is_wait_cs) {2391cs->signal_fence = sig_fence;2392/* store the handle pointer, so we don't have to2393* look for it again, later on the flow2394* when we need to set SOB info in hw_queue.2395*/2396if (cs->encaps_signals)2397cs->encaps_sig_hdl = encaps_sig_hdl;2398}23992400hl_debugfs_add_cs(cs);24012402*cs_seq = cs->sequence;24032404if (cs_type == CS_TYPE_WAIT || cs_type == CS_TYPE_SIGNAL)2405rc = cs_ioctl_signal_wait_create_jobs(hdev, ctx, cs, q_type,2406q_idx, chunk->encaps_signal_offset);2407else if (cs_type == CS_TYPE_COLLECTIVE_WAIT)2408rc = hdev->asic_funcs->collective_wait_create_jobs(hdev, ctx,2409cs, q_idx, collective_engine_id,2410chunk->encaps_signal_offset);2411else {2412atomic64_inc(&ctx->cs_counters.validation_drop_cnt);2413atomic64_inc(&cntr->validation_drop_cnt);2414rc = -EINVAL;2415}24162417if (rc)2418goto free_cs_object;24192420if (q_type == QUEUE_TYPE_HW)2421INIT_WORK(&cs->finish_work, cs_completion);24222423rc = hl_hw_queue_schedule_cs(cs);2424if (rc) {2425/* In case wait cs failed here, it means the signal cs2426* already completed. we want to free all it's related objects2427* but we don't want to fail the ioctl.2428*/2429if (is_wait_cs)2430rc = 0;2431else if (rc != -EAGAIN)2432dev_err(hdev->dev,2433"Failed to submit CS %d.%llu to H/W queues, error %d\n",2434ctx->asid, cs->sequence, rc);2435goto free_cs_object;2436}24372438*signal_sob_addr_offset = cs->sob_addr_offset;2439*signal_initial_sob_count = cs->initial_sob_count;24402441rc = HL_CS_STATUS_SUCCESS;2442if (is_wait_cs)2443wait_cs_submitted = true;2444goto put_cs;24452446free_cs_object:2447cs_rollback(hdev, cs);2448*cs_seq = ULLONG_MAX;2449/* The path below is both for good and erroneous exits */2450put_cs:2451/* We finished with the CS in this function, so put the ref */2452cs_put(cs);2453free_cs_chunk_array:2454if (!wait_cs_submitted && cs_encaps_signals && handle_found && is_wait_cs)2455kref_put(&encaps_sig_hdl->refcount, hl_encaps_release_handle_and_put_ctx);2456kfree(cs_chunk_array);2457out:2458return rc;2459}24602461static int cs_ioctl_engine_cores(struct hl_fpriv *hpriv, u64 engine_cores,2462u32 num_engine_cores, u32 core_command)2463{2464struct hl_device *hdev = hpriv->hdev;2465void __user *engine_cores_arr;2466u32 *cores;2467int rc;24682469if (!hdev->asic_prop.supports_engine_modes)2470return -EPERM;24712472if (!num_engine_cores || num_engine_cores > hdev->asic_prop.num_engine_cores) {2473dev_err(hdev->dev, "Number of engine cores %d is invalid\n", num_engine_cores);2474return -EINVAL;2475}24762477if (core_command != HL_ENGINE_CORE_RUN && core_command != HL_ENGINE_CORE_HALT) {2478dev_err(hdev->dev, "Engine core command is invalid\n");2479return -EINVAL;2480}24812482engine_cores_arr = (void __user *) (uintptr_t) engine_cores;2483cores = kmalloc_array(num_engine_cores, sizeof(u32), GFP_KERNEL);2484if (!cores)2485return -ENOMEM;24862487if (copy_from_user(cores, engine_cores_arr, num_engine_cores * sizeof(u32))) {2488dev_err(hdev->dev, "Failed to copy core-ids array from user\n");2489kfree(cores);2490return -EFAULT;2491}24922493rc = hdev->asic_funcs->set_engine_cores(hdev, cores, num_engine_cores, core_command);2494kfree(cores);24952496return rc;2497}24982499static int cs_ioctl_engines(struct hl_fpriv *hpriv, u64 engines_arr_user_addr,2500u32 num_engines, enum hl_engine_command command)2501{2502struct hl_device *hdev = hpriv->hdev;2503u32 *engines, max_num_of_engines;2504void __user *engines_arr;2505int rc;25062507if (!hdev->asic_prop.supports_engine_modes)2508return -EPERM;25092510if (command >= HL_ENGINE_COMMAND_MAX) {2511dev_err(hdev->dev, "Engine command is invalid\n");2512return -EINVAL;2513}25142515max_num_of_engines = hdev->asic_prop.max_num_of_engines;2516if (command == HL_ENGINE_CORE_RUN || command == HL_ENGINE_CORE_HALT)2517max_num_of_engines = hdev->asic_prop.num_engine_cores;25182519if (!num_engines || num_engines > max_num_of_engines) {2520dev_err(hdev->dev, "Number of engines %d is invalid\n", num_engines);2521return -EINVAL;2522}25232524engines_arr = (void __user *) (uintptr_t) engines_arr_user_addr;2525engines = kmalloc_array(num_engines, sizeof(u32), GFP_KERNEL);2526if (!engines)2527return -ENOMEM;25282529if (copy_from_user(engines, engines_arr, num_engines * sizeof(u32))) {2530dev_err(hdev->dev, "Failed to copy engine-ids array from user\n");2531kfree(engines);2532return -EFAULT;2533}25342535rc = hdev->asic_funcs->set_engines(hdev, engines, num_engines, command);2536kfree(engines);25372538return rc;2539}25402541static int cs_ioctl_flush_pci_hbw_writes(struct hl_fpriv *hpriv)2542{2543struct hl_device *hdev = hpriv->hdev;2544struct asic_fixed_properties *prop = &hdev->asic_prop;25452546if (!prop->hbw_flush_reg) {2547dev_dbg(hdev->dev, "HBW flush is not supported\n");2548return -EOPNOTSUPP;2549}25502551RREG32(prop->hbw_flush_reg);25522553return 0;2554}25552556int hl_cs_ioctl(struct drm_device *ddev, void *data, struct drm_file *file_priv)2557{2558struct hl_fpriv *hpriv = file_priv->driver_priv;2559union hl_cs_args *args = data;2560enum hl_cs_type cs_type = 0;2561u64 cs_seq = ULONG_MAX;2562void __user *chunks;2563u32 num_chunks, flags, timeout,2564signals_count = 0, sob_addr = 0, handle_id = 0;2565u16 sob_initial_count = 0;2566int rc;25672568rc = hl_cs_sanity_checks(hpriv, args);2569if (rc)2570goto out;25712572rc = hl_cs_ctx_switch(hpriv, args, &cs_seq);2573if (rc)2574goto out;25752576cs_type = hl_cs_get_cs_type(args->in.cs_flags &2577~HL_CS_FLAGS_FORCE_RESTORE);2578chunks = (void __user *) (uintptr_t) args->in.chunks_execute;2579num_chunks = args->in.num_chunks_execute;2580flags = args->in.cs_flags;25812582/* In case this is a staged CS, user should supply the CS sequence */2583if ((flags & HL_CS_FLAGS_STAGED_SUBMISSION) &&2584!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_FIRST))2585cs_seq = args->in.seq;25862587timeout = flags & HL_CS_FLAGS_CUSTOM_TIMEOUT2588? secs_to_jiffies(args->in.timeout)2589: hpriv->hdev->timeout_jiffies;25902591switch (cs_type) {2592case CS_TYPE_SIGNAL:2593case CS_TYPE_WAIT:2594case CS_TYPE_COLLECTIVE_WAIT:2595rc = cs_ioctl_signal_wait(hpriv, cs_type, chunks, num_chunks,2596&cs_seq, args->in.cs_flags, timeout,2597&sob_addr, &sob_initial_count);2598break;2599case CS_RESERVE_SIGNALS:2600rc = cs_ioctl_reserve_signals(hpriv,2601args->in.encaps_signals_q_idx,2602args->in.encaps_signals_count,2603&handle_id, &sob_addr, &signals_count);2604break;2605case CS_UNRESERVE_SIGNALS:2606rc = cs_ioctl_unreserve_signals(hpriv,2607args->in.encaps_sig_handle_id);2608break;2609case CS_TYPE_ENGINE_CORE:2610rc = cs_ioctl_engine_cores(hpriv, args->in.engine_cores,2611args->in.num_engine_cores, args->in.core_command);2612break;2613case CS_TYPE_ENGINES:2614rc = cs_ioctl_engines(hpriv, args->in.engines,2615args->in.num_engines, args->in.engine_command);2616break;2617case CS_TYPE_FLUSH_PCI_HBW_WRITES:2618rc = cs_ioctl_flush_pci_hbw_writes(hpriv);2619break;2620default:2621rc = cs_ioctl_default(hpriv, chunks, num_chunks, &cs_seq,2622args->in.cs_flags,2623args->in.encaps_sig_handle_id,2624timeout, &sob_initial_count);2625break;2626}2627out:2628if (rc != -EAGAIN) {2629memset(args, 0, sizeof(*args));26302631switch (cs_type) {2632case CS_RESERVE_SIGNALS:2633args->out.handle_id = handle_id;2634args->out.sob_base_addr_offset = sob_addr;2635args->out.count = signals_count;2636break;2637case CS_TYPE_SIGNAL:2638args->out.sob_base_addr_offset = sob_addr;2639args->out.sob_count_before_submission = sob_initial_count;2640args->out.seq = cs_seq;2641break;2642case CS_TYPE_DEFAULT:2643args->out.sob_count_before_submission = sob_initial_count;2644args->out.seq = cs_seq;2645break;2646default:2647args->out.seq = cs_seq;2648break;2649}26502651args->out.status = rc;2652}26532654return rc;2655}26562657static int hl_wait_for_fence(struct hl_ctx *ctx, u64 seq, struct hl_fence *fence,2658enum hl_cs_wait_status *status, u64 timeout_us, s64 *timestamp)2659{2660struct hl_device *hdev = ctx->hdev;2661ktime_t timestamp_kt;2662long completion_rc;2663int rc = 0, error;26642665if (IS_ERR(fence)) {2666rc = PTR_ERR(fence);2667if (rc == -EINVAL)2668dev_notice_ratelimited(hdev->dev,2669"Can't wait on CS %llu because current CS is at seq %llu\n",2670seq, ctx->cs_sequence);2671return rc;2672}26732674if (!fence) {2675if (!hl_pop_cs_outcome(&ctx->outcome_store, seq, ×tamp_kt, &error)) {2676dev_dbg(hdev->dev,2677"Can't wait on seq %llu because current CS is at seq %llu (Fence is gone)\n",2678seq, ctx->cs_sequence);2679*status = CS_WAIT_STATUS_GONE;2680return 0;2681}26822683completion_rc = 1;2684goto report_results;2685}26862687if (!timeout_us) {2688completion_rc = completion_done(&fence->completion);2689} else {2690unsigned long timeout;26912692timeout = (timeout_us == MAX_SCHEDULE_TIMEOUT) ?2693timeout_us : usecs_to_jiffies(timeout_us);2694completion_rc =2695wait_for_completion_interruptible_timeout(2696&fence->completion, timeout);2697}26982699error = fence->error;2700timestamp_kt = fence->timestamp;27012702report_results:2703if (completion_rc > 0) {2704*status = CS_WAIT_STATUS_COMPLETED;2705if (timestamp)2706*timestamp = ktime_to_ns(timestamp_kt);2707} else {2708*status = CS_WAIT_STATUS_BUSY;2709}27102711if (completion_rc == -ERESTARTSYS)2712rc = completion_rc;2713else if (error == -ETIMEDOUT || error == -EIO)2714rc = error;27152716return rc;2717}27182719/*2720* hl_cs_poll_fences - iterate CS fences to check for CS completion2721*2722* @mcs_data: multi-CS internal data2723* @mcs_compl: multi-CS completion structure2724*2725* @return 0 on success, otherwise non 0 error code2726*2727* The function iterates on all CS sequence in the list and set bit in2728* completion_bitmap for each completed CS.2729* While iterating, the function sets the stream map of each fence in the fence2730* array in the completion QID stream map to be used by CSs to perform2731* completion to the multi-CS context.2732* This function shall be called after taking context ref2733*/2734static int hl_cs_poll_fences(struct multi_cs_data *mcs_data, struct multi_cs_completion *mcs_compl)2735{2736struct hl_fence **fence_ptr = mcs_data->fence_arr;2737struct hl_device *hdev = mcs_data->ctx->hdev;2738int i, rc, arr_len = mcs_data->arr_len;2739u64 *seq_arr = mcs_data->seq_arr;2740ktime_t max_ktime, first_cs_time;2741enum hl_cs_wait_status status;27422743memset(fence_ptr, 0, arr_len * sizeof(struct hl_fence *));27442745/* get all fences under the same lock */2746rc = hl_ctx_get_fences(mcs_data->ctx, seq_arr, fence_ptr, arr_len);2747if (rc)2748return rc;27492750/*2751* re-initialize the completion here to handle 2 possible cases:2752* 1. CS will complete the multi-CS prior clearing the completion. in which2753* case the fence iteration is guaranteed to catch the CS completion.2754* 2. the completion will occur after re-init of the completion.2755* in which case we will wake up immediately in wait_for_completion.2756*/2757reinit_completion(&mcs_compl->completion);27582759/*2760* set to maximum time to verify timestamp is valid: if at the end2761* this value is maintained- no timestamp was updated2762*/2763max_ktime = ktime_set(KTIME_SEC_MAX, 0);2764first_cs_time = max_ktime;27652766for (i = 0; i < arr_len; i++, fence_ptr++) {2767struct hl_fence *fence = *fence_ptr;27682769/*2770* In order to prevent case where we wait until timeout even though a CS associated2771* with the multi-CS actually completed we do things in the below order:2772* 1. for each fence set it's QID map in the multi-CS completion QID map. This way2773* any CS can, potentially, complete the multi CS for the specific QID (note2774* that once completion is initialized, calling complete* and then wait on the2775* completion will cause it to return at once)2776* 2. only after allowing multi-CS completion for the specific QID we check whether2777* the specific CS already completed (and thus the wait for completion part will2778* be skipped). if the CS not completed it is guaranteed that completing CS will2779* wake up the completion.2780*/2781if (fence)2782mcs_compl->stream_master_qid_map |= fence->stream_master_qid_map;27832784/*2785* function won't sleep as it is called with timeout 0 (i.e.2786* poll the fence)2787*/2788rc = hl_wait_for_fence(mcs_data->ctx, seq_arr[i], fence, &status, 0, NULL);2789if (rc) {2790dev_err(hdev->dev,2791"wait_for_fence error :%d for CS seq %llu\n",2792rc, seq_arr[i]);2793break;2794}27952796switch (status) {2797case CS_WAIT_STATUS_BUSY:2798/* CS did not finished, QID to wait on already stored */2799break;2800case CS_WAIT_STATUS_COMPLETED:2801/*2802* Using mcs_handling_done to avoid possibility of mcs_data2803* returns to user indicating CS completed before it finished2804* all of its mcs handling, to avoid race the next time the2805* user waits for mcs.2806* note: when reaching this case fence is definitely not NULL2807* but NULL check was added to overcome static analysis2808*/2809if (fence && !fence->mcs_handling_done) {2810/*2811* in case multi CS is completed but MCS handling not done2812* we "complete" the multi CS to prevent it from waiting2813* until time-out and the "multi-CS handling done" will have2814* another chance at the next iteration2815*/2816complete_all(&mcs_compl->completion);2817break;2818}28192820mcs_data->completion_bitmap |= BIT(i);2821/*2822* For all completed CSs we take the earliest timestamp.2823* For this we have to validate that the timestamp is2824* earliest of all timestamps so far.2825*/2826if (fence && mcs_data->update_ts &&2827(ktime_compare(fence->timestamp, first_cs_time) < 0))2828first_cs_time = fence->timestamp;2829break;2830case CS_WAIT_STATUS_GONE:2831mcs_data->update_ts = false;2832mcs_data->gone_cs = true;2833/*2834* It is possible to get an old sequence numbers from user2835* which related to already completed CSs and their fences2836* already gone. In this case, CS set as completed but2837* no need to consider its QID for mcs completion.2838*/2839mcs_data->completion_bitmap |= BIT(i);2840break;2841default:2842dev_err(hdev->dev, "Invalid fence status\n");2843rc = -EINVAL;2844break;2845}28462847}28482849hl_fences_put(mcs_data->fence_arr, arr_len);28502851if (mcs_data->update_ts &&2852(ktime_compare(first_cs_time, max_ktime) != 0))2853mcs_data->timestamp = ktime_to_ns(first_cs_time);28542855return rc;2856}28572858static int _hl_cs_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx, u64 timeout_us, u64 seq,2859enum hl_cs_wait_status *status, s64 *timestamp)2860{2861struct hl_fence *fence;2862int rc = 0;28632864if (timestamp)2865*timestamp = 0;28662867hl_ctx_get(ctx);28682869fence = hl_ctx_get_fence(ctx, seq);28702871rc = hl_wait_for_fence(ctx, seq, fence, status, timeout_us, timestamp);2872hl_fence_put(fence);2873hl_ctx_put(ctx);28742875return rc;2876}28772878static inline unsigned long hl_usecs64_to_jiffies(const u64 usecs)2879{2880if (usecs <= U32_MAX)2881return usecs_to_jiffies(usecs);28822883/*2884* If the value in nanoseconds is larger than 64 bit, use the largest2885* 64 bit value.2886*/2887if (usecs >= ((u64)(U64_MAX / NSEC_PER_USEC)))2888return nsecs_to_jiffies(U64_MAX);28892890return nsecs_to_jiffies(usecs * NSEC_PER_USEC);2891}28922893/*2894* hl_wait_multi_cs_completion_init - init completion structure2895*2896* @hdev: pointer to habanalabs device structure2897* @stream_master_bitmap: stream master QIDs map, set bit indicates stream2898* master QID to wait on2899*2900* @return valid completion struct pointer on success, otherwise error pointer2901*2902* up to MULTI_CS_MAX_USER_CTX calls can be done concurrently to the driver.2903* the function gets the first available completion (by marking it "used")2904* and initialize its values.2905*/2906static struct multi_cs_completion *hl_wait_multi_cs_completion_init(struct hl_device *hdev)2907{2908struct multi_cs_completion *mcs_compl;2909int i;29102911/* find free multi_cs completion structure */2912for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {2913mcs_compl = &hdev->multi_cs_completion[i];2914spin_lock(&mcs_compl->lock);2915if (!mcs_compl->used) {2916mcs_compl->used = 1;2917mcs_compl->timestamp = 0;2918/*2919* init QID map to 0 to avoid completion by CSs. the actual QID map2920* to multi-CS CSs will be set incrementally at a later stage2921*/2922mcs_compl->stream_master_qid_map = 0;2923spin_unlock(&mcs_compl->lock);2924break;2925}2926spin_unlock(&mcs_compl->lock);2927}29282929if (i == MULTI_CS_MAX_USER_CTX) {2930dev_err(hdev->dev, "no available multi-CS completion structure\n");2931return ERR_PTR(-ENOMEM);2932}2933return mcs_compl;2934}29352936/*2937* hl_wait_multi_cs_completion_fini - return completion structure and set as2938* unused2939*2940* @mcs_compl: pointer to the completion structure2941*/2942static void hl_wait_multi_cs_completion_fini(2943struct multi_cs_completion *mcs_compl)2944{2945/*2946* free completion structure, do it under lock to be in-sync with the2947* thread that signals completion2948*/2949spin_lock(&mcs_compl->lock);2950mcs_compl->used = 0;2951spin_unlock(&mcs_compl->lock);2952}29532954/*2955* hl_wait_multi_cs_completion - wait for first CS to complete2956*2957* @mcs_data: multi-CS internal data2958*2959* @return 0 on success, otherwise non 0 error code2960*/2961static int hl_wait_multi_cs_completion(struct multi_cs_data *mcs_data,2962struct multi_cs_completion *mcs_compl)2963{2964long completion_rc;29652966completion_rc = wait_for_completion_interruptible_timeout(&mcs_compl->completion,2967mcs_data->timeout_jiffies);29682969/* update timestamp */2970if (completion_rc > 0)2971mcs_data->timestamp = mcs_compl->timestamp;29722973if (completion_rc == -ERESTARTSYS)2974return completion_rc;29752976mcs_data->wait_status = completion_rc;29772978return 0;2979}29802981/*2982* hl_multi_cs_completion_init - init array of multi-CS completion structures2983*2984* @hdev: pointer to habanalabs device structure2985*/2986void hl_multi_cs_completion_init(struct hl_device *hdev)2987{2988struct multi_cs_completion *mcs_cmpl;2989int i;29902991for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {2992mcs_cmpl = &hdev->multi_cs_completion[i];2993mcs_cmpl->used = 0;2994spin_lock_init(&mcs_cmpl->lock);2995init_completion(&mcs_cmpl->completion);2996}2997}29982999/*3000* hl_multi_cs_wait_ioctl - implementation of the multi-CS wait ioctl3001*3002* @hpriv: pointer to the private data of the fd3003* @data: pointer to multi-CS wait ioctl in/out args3004*3005*/3006static int hl_multi_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data)3007{3008struct multi_cs_completion *mcs_compl;3009struct hl_device *hdev = hpriv->hdev;3010struct multi_cs_data mcs_data = {};3011union hl_wait_cs_args *args = data;3012struct hl_ctx *ctx = hpriv->ctx;3013struct hl_fence **fence_arr;3014void __user *seq_arr;3015u32 size_to_copy;3016u64 *cs_seq_arr;3017u8 seq_arr_len;3018int rc, i;30193020for (i = 0 ; i < sizeof(args->in.pad) ; i++)3021if (args->in.pad[i]) {3022dev_dbg(hdev->dev, "Padding bytes must be 0\n");3023return -EINVAL;3024}30253026if (!hdev->supports_wait_for_multi_cs) {3027dev_err(hdev->dev, "Wait for multi CS is not supported\n");3028return -EPERM;3029}30303031seq_arr_len = args->in.seq_arr_len;30323033if (seq_arr_len > HL_WAIT_MULTI_CS_LIST_MAX_LEN) {3034dev_err(hdev->dev, "Can wait only up to %d CSs, input sequence is of length %u\n",3035HL_WAIT_MULTI_CS_LIST_MAX_LEN, seq_arr_len);3036return -EINVAL;3037}30383039/* allocate memory for sequence array */3040cs_seq_arr =3041kmalloc_array(seq_arr_len, sizeof(*cs_seq_arr), GFP_KERNEL);3042if (!cs_seq_arr)3043return -ENOMEM;30443045/* copy CS sequence array from user */3046seq_arr = (void __user *) (uintptr_t) args->in.seq;3047size_to_copy = seq_arr_len * sizeof(*cs_seq_arr);3048if (copy_from_user(cs_seq_arr, seq_arr, size_to_copy)) {3049dev_err(hdev->dev, "Failed to copy multi-cs sequence array from user\n");3050rc = -EFAULT;3051goto free_seq_arr;3052}30533054/* allocate array for the fences */3055fence_arr = kmalloc_array(seq_arr_len, sizeof(struct hl_fence *), GFP_KERNEL);3056if (!fence_arr) {3057rc = -ENOMEM;3058goto free_seq_arr;3059}30603061/* initialize the multi-CS internal data */3062mcs_data.ctx = ctx;3063mcs_data.seq_arr = cs_seq_arr;3064mcs_data.fence_arr = fence_arr;3065mcs_data.arr_len = seq_arr_len;30663067hl_ctx_get(ctx);30683069/* wait (with timeout) for the first CS to be completed */3070mcs_data.timeout_jiffies = hl_usecs64_to_jiffies(args->in.timeout_us);3071mcs_compl = hl_wait_multi_cs_completion_init(hdev);3072if (IS_ERR(mcs_compl)) {3073rc = PTR_ERR(mcs_compl);3074goto put_ctx;3075}30763077/* poll all CS fences, extract timestamp */3078mcs_data.update_ts = true;3079rc = hl_cs_poll_fences(&mcs_data, mcs_compl);3080/*3081* skip wait for CS completion when one of the below is true:3082* - an error on the poll function3083* - one or more CS in the list completed3084* - the user called ioctl with timeout 03085*/3086if (rc || mcs_data.completion_bitmap || !args->in.timeout_us)3087goto completion_fini;30883089while (true) {3090rc = hl_wait_multi_cs_completion(&mcs_data, mcs_compl);3091if (rc || (mcs_data.wait_status == 0))3092break;30933094/*3095* poll fences once again to update the CS map.3096* no timestamp should be updated this time.3097*/3098mcs_data.update_ts = false;3099rc = hl_cs_poll_fences(&mcs_data, mcs_compl);31003101if (rc || mcs_data.completion_bitmap)3102break;31033104/*3105* if hl_wait_multi_cs_completion returned before timeout (i.e.3106* it got a completion) it either got completed by CS in the multi CS list3107* (in which case the indication will be non empty completion_bitmap) or it3108* got completed by CS submitted to one of the shared stream master but3109* not in the multi CS list (in which case we should wait again but modify3110* the timeout and set timestamp as zero to let a CS related to the current3111* multi-CS set a new, relevant, timestamp)3112*/3113mcs_data.timeout_jiffies = mcs_data.wait_status;3114mcs_compl->timestamp = 0;3115}31163117completion_fini:3118hl_wait_multi_cs_completion_fini(mcs_compl);31193120put_ctx:3121hl_ctx_put(ctx);3122kfree(fence_arr);31233124free_seq_arr:3125kfree(cs_seq_arr);31263127if (rc == -ERESTARTSYS) {3128dev_err_ratelimited(hdev->dev,3129"user process got signal while waiting for Multi-CS\n");3130rc = -EINTR;3131}31323133if (rc)3134return rc;31353136/* update output args */3137memset(args, 0, sizeof(*args));31383139if (mcs_data.completion_bitmap) {3140args->out.status = HL_WAIT_CS_STATUS_COMPLETED;3141args->out.cs_completion_map = mcs_data.completion_bitmap;31423143/* if timestamp not 0- it's valid */3144if (mcs_data.timestamp) {3145args->out.timestamp_nsec = mcs_data.timestamp;3146args->out.flags |= HL_WAIT_CS_STATUS_FLAG_TIMESTAMP_VLD;3147}31483149/* update if some CS was gone */3150if (!mcs_data.timestamp)3151args->out.flags |= HL_WAIT_CS_STATUS_FLAG_GONE;3152} else {3153args->out.status = HL_WAIT_CS_STATUS_BUSY;3154}31553156return 0;3157}31583159static int hl_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data)3160{3161struct hl_device *hdev = hpriv->hdev;3162union hl_wait_cs_args *args = data;3163enum hl_cs_wait_status status;3164u64 seq = args->in.seq;3165s64 timestamp;3166int rc;31673168rc = _hl_cs_wait_ioctl(hdev, hpriv->ctx, args->in.timeout_us, seq, &status, ×tamp);31693170if (rc == -ERESTARTSYS) {3171dev_err_ratelimited(hdev->dev,3172"user process got signal while waiting for CS handle %llu\n",3173seq);3174return -EINTR;3175}31763177memset(args, 0, sizeof(*args));31783179if (rc) {3180if (rc == -ETIMEDOUT) {3181dev_err_ratelimited(hdev->dev,3182"CS %llu has timed-out while user process is waiting for it\n",3183seq);3184args->out.status = HL_WAIT_CS_STATUS_TIMEDOUT;3185} else if (rc == -EIO) {3186dev_err_ratelimited(hdev->dev,3187"CS %llu has been aborted while user process is waiting for it\n",3188seq);3189args->out.status = HL_WAIT_CS_STATUS_ABORTED;3190}3191return rc;3192}31933194if (timestamp) {3195args->out.flags |= HL_WAIT_CS_STATUS_FLAG_TIMESTAMP_VLD;3196args->out.timestamp_nsec = timestamp;3197}31983199switch (status) {3200case CS_WAIT_STATUS_GONE:3201args->out.flags |= HL_WAIT_CS_STATUS_FLAG_GONE;3202fallthrough;3203case CS_WAIT_STATUS_COMPLETED:3204args->out.status = HL_WAIT_CS_STATUS_COMPLETED;3205break;3206case CS_WAIT_STATUS_BUSY:3207default:3208args->out.status = HL_WAIT_CS_STATUS_BUSY;3209break;3210}32113212return 0;3213}32143215static inline void set_record_cq_info(struct hl_user_pending_interrupt *record,3216struct hl_cb *cq_cb, u32 cq_offset, u32 target_value)3217{3218record->ts_reg_info.cq_cb = cq_cb;3219record->cq_kernel_addr = (u64 *) cq_cb->kernel_address + cq_offset;3220record->cq_target_value = target_value;3221}32223223static int validate_and_get_ts_record(struct device *dev,3224struct hl_ts_buff *ts_buff, u64 ts_offset,3225struct hl_user_pending_interrupt **req_event_record)3226{3227struct hl_user_pending_interrupt *ts_cb_last;32283229*req_event_record = (struct hl_user_pending_interrupt *)ts_buff->kernel_buff_address +3230ts_offset;3231ts_cb_last = (struct hl_user_pending_interrupt *)ts_buff->kernel_buff_address +3232(ts_buff->kernel_buff_size / sizeof(struct hl_user_pending_interrupt));32333234/* Validate ts_offset not exceeding last max */3235if (*req_event_record >= ts_cb_last) {3236dev_err(dev, "Ts offset(%llu) exceeds max CB offset(0x%llx)\n",3237ts_offset, (u64)(uintptr_t)ts_cb_last);3238return -EINVAL;3239}32403241return 0;3242}32433244static void unregister_timestamp_node(struct hl_device *hdev,3245struct hl_user_pending_interrupt *record, bool need_lock)3246{3247struct hl_user_interrupt *interrupt = record->ts_reg_info.interrupt;3248bool ts_rec_found = false;3249unsigned long flags;32503251if (need_lock)3252spin_lock_irqsave(&interrupt->ts_list_lock, flags);32533254if (record->ts_reg_info.in_use) {3255record->ts_reg_info.in_use = false;3256list_del(&record->list_node);3257ts_rec_found = true;3258}32593260if (need_lock)3261spin_unlock_irqrestore(&interrupt->ts_list_lock, flags);32623263/* Put refcounts that were taken when we registered the event */3264if (ts_rec_found) {3265hl_mmap_mem_buf_put(record->ts_reg_info.buf);3266hl_cb_put(record->ts_reg_info.cq_cb);3267}3268}32693270static int ts_get_and_handle_kernel_record(struct hl_device *hdev, struct hl_ctx *ctx,3271struct wait_interrupt_data *data, unsigned long *flags,3272struct hl_user_pending_interrupt **pend)3273{3274struct hl_user_pending_interrupt *req_offset_record;3275struct hl_ts_buff *ts_buff = data->buf->private;3276bool need_lock = false;3277int rc;32783279rc = validate_and_get_ts_record(data->buf->mmg->dev, ts_buff, data->ts_offset,3280&req_offset_record);3281if (rc)3282return rc;32833284/* In case the node already registered, need to unregister first then re-use */3285if (req_offset_record->ts_reg_info.in_use) {3286/*3287* Since interrupt here can be different than the one the node currently registered3288* on, and we don't want to lock two lists while we're doing unregister, so3289* unlock the new interrupt wait list here and acquire the lock again after you done3290*/3291if (data->interrupt->interrupt_id !=3292req_offset_record->ts_reg_info.interrupt->interrupt_id) {32933294need_lock = true;3295spin_unlock_irqrestore(&data->interrupt->ts_list_lock, *flags);3296}32973298unregister_timestamp_node(hdev, req_offset_record, need_lock);32993300if (need_lock)3301spin_lock_irqsave(&data->interrupt->ts_list_lock, *flags);3302}33033304/* Fill up the new registration node info and add it to the list */3305req_offset_record->ts_reg_info.in_use = true;3306req_offset_record->ts_reg_info.buf = data->buf;3307req_offset_record->ts_reg_info.timestamp_kernel_addr =3308(u64 *) ts_buff->user_buff_address + data->ts_offset;3309req_offset_record->ts_reg_info.interrupt = data->interrupt;3310set_record_cq_info(req_offset_record, data->cq_cb, data->cq_offset,3311data->target_value);33123313*pend = req_offset_record;33143315return rc;3316}33173318static int _hl_interrupt_ts_reg_ioctl(struct hl_device *hdev, struct hl_ctx *ctx,3319struct wait_interrupt_data *data,3320u32 *status, u64 *timestamp)3321{3322struct hl_user_pending_interrupt *pend;3323unsigned long flags;3324int rc = 0;33253326hl_ctx_get(ctx);33273328data->cq_cb = hl_cb_get(data->mmg, data->cq_handle);3329if (!data->cq_cb) {3330rc = -EINVAL;3331goto put_ctx;3332}33333334/* Validate the cq offset */3335if (((u64 *) data->cq_cb->kernel_address + data->cq_offset) >=3336((u64 *) data->cq_cb->kernel_address + (data->cq_cb->size / sizeof(u64)))) {3337rc = -EINVAL;3338goto put_cq_cb;3339}33403341data->buf = hl_mmap_mem_buf_get(data->mmg, data->ts_handle);3342if (!data->buf) {3343rc = -EINVAL;3344goto put_cq_cb;3345}33463347spin_lock_irqsave(&data->interrupt->ts_list_lock, flags);33483349/* get ts buffer record */3350rc = ts_get_and_handle_kernel_record(hdev, ctx, data, &flags, &pend);3351if (rc) {3352spin_unlock_irqrestore(&data->interrupt->ts_list_lock, flags);3353goto put_ts_buff;3354}33553356/* We check for completion value as interrupt could have been received3357* before we add the timestamp node to the ts list.3358*/3359if (*pend->cq_kernel_addr >= data->target_value) {3360spin_unlock_irqrestore(&data->interrupt->ts_list_lock, flags);33613362pend->ts_reg_info.in_use = 0;3363*status = HL_WAIT_CS_STATUS_COMPLETED;3364*pend->ts_reg_info.timestamp_kernel_addr = ktime_get_ns();33653366goto put_ts_buff;3367}33683369list_add_tail(&pend->list_node, &data->interrupt->ts_list_head);3370spin_unlock_irqrestore(&data->interrupt->ts_list_lock, flags);33713372rc = *status = HL_WAIT_CS_STATUS_COMPLETED;33733374hl_ctx_put(ctx);33753376return rc;33773378put_ts_buff:3379hl_mmap_mem_buf_put(data->buf);3380put_cq_cb:3381hl_cb_put(data->cq_cb);3382put_ctx:3383hl_ctx_put(ctx);33843385return rc;3386}33873388static int _hl_interrupt_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx,3389struct wait_interrupt_data *data,3390u32 *status, u64 *timestamp)3391{3392struct hl_user_pending_interrupt *pend;3393unsigned long timeout, flags;3394long completion_rc;3395int rc = 0;33963397timeout = hl_usecs64_to_jiffies(data->intr_timeout_us);33983399hl_ctx_get(ctx);34003401data->cq_cb = hl_cb_get(data->mmg, data->cq_handle);3402if (!data->cq_cb) {3403rc = -EINVAL;3404goto put_ctx;3405}34063407/* Validate the cq offset */3408if (((u64 *) data->cq_cb->kernel_address + data->cq_offset) >=3409((u64 *) data->cq_cb->kernel_address + (data->cq_cb->size / sizeof(u64)))) {3410rc = -EINVAL;3411goto put_cq_cb;3412}34133414pend = kzalloc(sizeof(*pend), GFP_KERNEL);3415if (!pend) {3416rc = -ENOMEM;3417goto put_cq_cb;3418}34193420hl_fence_init(&pend->fence, ULONG_MAX);3421pend->cq_kernel_addr = (u64 *) data->cq_cb->kernel_address + data->cq_offset;3422pend->cq_target_value = data->target_value;3423spin_lock_irqsave(&data->interrupt->wait_list_lock, flags);342434253426/* We check for completion value as interrupt could have been received3427* before we add the wait node to the wait list.3428*/3429if (*pend->cq_kernel_addr >= data->target_value || (!data->intr_timeout_us)) {3430spin_unlock_irqrestore(&data->interrupt->wait_list_lock, flags);34313432if (*pend->cq_kernel_addr >= data->target_value)3433*status = HL_WAIT_CS_STATUS_COMPLETED;3434else3435*status = HL_WAIT_CS_STATUS_BUSY;34363437pend->fence.timestamp = ktime_get();3438goto set_timestamp;3439}34403441/* Add pending user interrupt to relevant list for the interrupt3442* handler to monitor.3443* Note that we cannot have sorted list by target value,3444* in order to shorten the list pass loop, since3445* same list could have nodes for different cq counter handle.3446*/3447list_add_tail(&pend->list_node, &data->interrupt->wait_list_head);3448spin_unlock_irqrestore(&data->interrupt->wait_list_lock, flags);34493450/* Wait for interrupt handler to signal completion */3451completion_rc = wait_for_completion_interruptible_timeout(&pend->fence.completion,3452timeout);3453if (completion_rc > 0) {3454if (pend->fence.error == -EIO) {3455dev_err_ratelimited(hdev->dev,3456"interrupt based wait ioctl aborted(error:%d) due to a reset cycle initiated\n",3457pend->fence.error);3458rc = -EIO;3459*status = HL_WAIT_CS_STATUS_ABORTED;3460} else {3461*status = HL_WAIT_CS_STATUS_COMPLETED;3462}3463} else {3464if (completion_rc == -ERESTARTSYS) {3465dev_err_ratelimited(hdev->dev,3466"user process got signal while waiting for interrupt ID %d\n",3467data->interrupt->interrupt_id);3468rc = -EINTR;3469*status = HL_WAIT_CS_STATUS_ABORTED;3470} else {3471/* The wait has timed-out. We don't know anything beyond that3472* because the workload was not submitted through the driver.3473* Therefore, from driver's perspective, the workload is still3474* executing.3475*/3476rc = 0;3477*status = HL_WAIT_CS_STATUS_BUSY;3478}3479}34803481/*3482* We keep removing the node from list here, and not at the irq handler3483* for completion timeout case. and if it's a registration3484* for ts record, the node will be deleted in the irq handler after3485* we reach the target value.3486*/3487spin_lock_irqsave(&data->interrupt->wait_list_lock, flags);3488list_del(&pend->list_node);3489spin_unlock_irqrestore(&data->interrupt->wait_list_lock, flags);34903491set_timestamp:3492*timestamp = ktime_to_ns(pend->fence.timestamp);3493kfree(pend);3494hl_cb_put(data->cq_cb);3495hl_ctx_put(ctx);34963497return rc;34983499put_cq_cb:3500hl_cb_put(data->cq_cb);3501put_ctx:3502hl_ctx_put(ctx);35033504return rc;3505}35063507static int _hl_interrupt_wait_ioctl_user_addr(struct hl_device *hdev, struct hl_ctx *ctx,3508u64 timeout_us, u64 user_address,3509u64 target_value, struct hl_user_interrupt *interrupt,3510u32 *status,3511u64 *timestamp)3512{3513struct hl_user_pending_interrupt *pend;3514unsigned long timeout, flags;3515u64 completion_value;3516long completion_rc;3517int rc = 0;35183519timeout = hl_usecs64_to_jiffies(timeout_us);35203521hl_ctx_get(ctx);35223523pend = kzalloc(sizeof(*pend), GFP_KERNEL);3524if (!pend) {3525hl_ctx_put(ctx);3526return -ENOMEM;3527}35283529hl_fence_init(&pend->fence, ULONG_MAX);35303531/* Add pending user interrupt to relevant list for the interrupt3532* handler to monitor3533*/3534spin_lock_irqsave(&interrupt->wait_list_lock, flags);3535list_add_tail(&pend->list_node, &interrupt->wait_list_head);3536spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);35373538/* We check for completion value as interrupt could have been received3539* before we added the node to the wait list3540*/3541if (copy_from_user(&completion_value, u64_to_user_ptr(user_address), 8)) {3542dev_err(hdev->dev, "Failed to copy completion value from user\n");3543rc = -EFAULT;3544goto remove_pending_user_interrupt;3545}35463547if (completion_value >= target_value) {3548*status = HL_WAIT_CS_STATUS_COMPLETED;3549/* There was no interrupt, we assume the completion is now. */3550pend->fence.timestamp = ktime_get();3551} else {3552*status = HL_WAIT_CS_STATUS_BUSY;3553}35543555if (!timeout_us || (*status == HL_WAIT_CS_STATUS_COMPLETED))3556goto remove_pending_user_interrupt;35573558wait_again:3559/* Wait for interrupt handler to signal completion */3560completion_rc = wait_for_completion_interruptible_timeout(&pend->fence.completion,3561timeout);35623563/* If timeout did not expire we need to perform the comparison.3564* If comparison fails, keep waiting until timeout expires3565*/3566if (completion_rc > 0) {3567spin_lock_irqsave(&interrupt->wait_list_lock, flags);3568/* reinit_completion must be called before we check for user3569* completion value, otherwise, if interrupt is received after3570* the comparison and before the next wait_for_completion,3571* we will reach timeout and fail3572*/3573reinit_completion(&pend->fence.completion);3574spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);35753576if (copy_from_user(&completion_value, u64_to_user_ptr(user_address), 8)) {3577dev_err(hdev->dev, "Failed to copy completion value from user\n");3578rc = -EFAULT;35793580goto remove_pending_user_interrupt;3581}35823583if (completion_value >= target_value) {3584*status = HL_WAIT_CS_STATUS_COMPLETED;3585} else if (pend->fence.error) {3586dev_err_ratelimited(hdev->dev,3587"interrupt based wait ioctl aborted(error:%d) due to a reset cycle initiated\n",3588pend->fence.error);3589/* set the command completion status as ABORTED */3590*status = HL_WAIT_CS_STATUS_ABORTED;3591} else {3592timeout = completion_rc;3593goto wait_again;3594}3595} else if (completion_rc == -ERESTARTSYS) {3596dev_err_ratelimited(hdev->dev,3597"user process got signal while waiting for interrupt ID %d\n",3598interrupt->interrupt_id);3599rc = -EINTR;3600} else {3601/* The wait has timed-out. We don't know anything beyond that3602* because the workload wasn't submitted through the driver.3603* Therefore, from driver's perspective, the workload is still3604* executing.3605*/3606rc = 0;3607*status = HL_WAIT_CS_STATUS_BUSY;3608}36093610remove_pending_user_interrupt:3611spin_lock_irqsave(&interrupt->wait_list_lock, flags);3612list_del(&pend->list_node);3613spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);36143615*timestamp = ktime_to_ns(pend->fence.timestamp);36163617kfree(pend);3618hl_ctx_put(ctx);36193620return rc;3621}36223623static int hl_interrupt_wait_ioctl(struct hl_fpriv *hpriv, void *data)3624{3625u16 interrupt_id, first_interrupt, last_interrupt;3626struct hl_device *hdev = hpriv->hdev;3627struct asic_fixed_properties *prop;3628struct hl_user_interrupt *interrupt;3629union hl_wait_cs_args *args = data;3630u32 status = HL_WAIT_CS_STATUS_BUSY;3631u64 timestamp = 0;3632int rc, int_idx;36333634prop = &hdev->asic_prop;36353636if (!(prop->user_interrupt_count + prop->user_dec_intr_count)) {3637dev_err(hdev->dev, "no user interrupts allowed");3638return -EPERM;3639}36403641interrupt_id = FIELD_GET(HL_WAIT_CS_FLAGS_INTERRUPT_MASK, args->in.flags);36423643first_interrupt = prop->first_available_user_interrupt;3644last_interrupt = prop->first_available_user_interrupt + prop->user_interrupt_count - 1;36453646if (interrupt_id < prop->user_dec_intr_count) {36473648/* Check if the requested core is enabled */3649if (!(prop->decoder_enabled_mask & BIT(interrupt_id))) {3650dev_err(hdev->dev, "interrupt on a disabled core(%u) not allowed",3651interrupt_id);3652return -EINVAL;3653}36543655interrupt = &hdev->user_interrupt[interrupt_id];36563657} else if (interrupt_id >= first_interrupt && interrupt_id <= last_interrupt) {36583659int_idx = interrupt_id - first_interrupt + prop->user_dec_intr_count;3660interrupt = &hdev->user_interrupt[int_idx];36613662} else if (interrupt_id == HL_COMMON_USER_CQ_INTERRUPT_ID) {3663interrupt = &hdev->common_user_cq_interrupt;3664} else if (interrupt_id == HL_COMMON_DEC_INTERRUPT_ID) {3665interrupt = &hdev->common_decoder_interrupt;3666} else {3667dev_err(hdev->dev, "invalid user interrupt %u", interrupt_id);3668return -EINVAL;3669}36703671if (args->in.flags & HL_WAIT_CS_FLAGS_INTERRUPT_KERNEL_CQ) {3672struct wait_interrupt_data wait_intr_data = {0};36733674wait_intr_data.interrupt = interrupt;3675wait_intr_data.mmg = &hpriv->mem_mgr;3676wait_intr_data.cq_handle = args->in.cq_counters_handle;3677wait_intr_data.cq_offset = args->in.cq_counters_offset;3678wait_intr_data.ts_handle = args->in.timestamp_handle;3679wait_intr_data.ts_offset = args->in.timestamp_offset;3680wait_intr_data.target_value = args->in.target;3681wait_intr_data.intr_timeout_us = args->in.interrupt_timeout_us;36823683if (args->in.flags & HL_WAIT_CS_FLAGS_REGISTER_INTERRUPT) {3684/*3685* Allow only one registration at a time. this is needed in order to prevent3686* issues while handling the flow of re-use of the same offset.3687* Since the registration flow is protected only by the interrupt lock,3688* re-use flow might request to move ts node to another interrupt list,3689* and in such case we're not protected.3690*/3691mutex_lock(&hpriv->ctx->ts_reg_lock);36923693rc = _hl_interrupt_ts_reg_ioctl(hdev, hpriv->ctx, &wait_intr_data,3694&status, ×tamp);36953696mutex_unlock(&hpriv->ctx->ts_reg_lock);3697} else3698rc = _hl_interrupt_wait_ioctl(hdev, hpriv->ctx, &wait_intr_data,3699&status, ×tamp);3700} else {3701rc = _hl_interrupt_wait_ioctl_user_addr(hdev, hpriv->ctx,3702args->in.interrupt_timeout_us, args->in.addr,3703args->in.target, interrupt, &status,3704×tamp);3705}37063707if (rc)3708return rc;37093710memset(args, 0, sizeof(*args));3711args->out.status = status;37123713if (timestamp) {3714args->out.timestamp_nsec = timestamp;3715args->out.flags |= HL_WAIT_CS_STATUS_FLAG_TIMESTAMP_VLD;3716}37173718return 0;3719}37203721int hl_wait_ioctl(struct drm_device *ddev, void *data, struct drm_file *file_priv)3722{3723struct hl_fpriv *hpriv = file_priv->driver_priv;3724struct hl_device *hdev = hpriv->hdev;3725union hl_wait_cs_args *args = data;3726u32 flags = args->in.flags;3727int rc;37283729/* If the device is not operational, or if an error has happened and user should release the3730* device, there is no point in waiting for any command submission or user interrupt.3731*/3732if (!hl_device_operational(hpriv->hdev, NULL) || hdev->reset_info.watchdog_active)3733return -EBUSY;37343735if (flags & HL_WAIT_CS_FLAGS_INTERRUPT)3736rc = hl_interrupt_wait_ioctl(hpriv, data);3737else if (flags & HL_WAIT_CS_FLAGS_MULTI_CS)3738rc = hl_multi_cs_wait_ioctl(hpriv, data);3739else3740rc = hl_cs_wait_ioctl(hpriv, data);37413742return rc;3743}374437453746