// SPDX-License-Identifier: GPL-2.01/*2* Functions to sequence PREFLUSH and FUA writes.3*4* Copyright (C) 2011 Max Planck Institute for Gravitational Physics5* Copyright (C) 2011 Tejun Heo <[email protected]>6*7* REQ_{PREFLUSH|FUA} requests are decomposed to sequences consisted of three8* optional steps - PREFLUSH, DATA and POSTFLUSH - according to the request9* properties and hardware capability.10*11* If a request doesn't have data, only REQ_PREFLUSH makes sense, which12* indicates a simple flush request. If there is data, REQ_PREFLUSH indicates13* that the device cache should be flushed before the data is executed, and14* REQ_FUA means that the data must be on non-volatile media on request15* completion.16*17* If the device doesn't have writeback cache, PREFLUSH and FUA don't make any18* difference. The requests are either completed immediately if there's no data19* or executed as normal requests otherwise.20*21* If the device has writeback cache and supports FUA, REQ_PREFLUSH is22* translated to PREFLUSH but REQ_FUA is passed down directly with DATA.23*24* If the device has writeback cache and doesn't support FUA, REQ_PREFLUSH25* is translated to PREFLUSH and REQ_FUA to POSTFLUSH.26*27* The actual execution of flush is double buffered. Whenever a request28* needs to execute PRE or POSTFLUSH, it queues at29* fq->flush_queue[fq->flush_pending_idx]. Once certain criteria are met, a30* REQ_OP_FLUSH is issued and the pending_idx is toggled. When the flush31* completes, all the requests which were pending are proceeded to the next32* step. This allows arbitrary merging of different types of PREFLUSH/FUA33* requests.34*35* Currently, the following conditions are used to determine when to issue36* flush.37*38* C1. At any given time, only one flush shall be in progress. This makes39* double buffering sufficient.40*41* C2. Flush is deferred if any request is executing DATA of its sequence.42* This avoids issuing separate POSTFLUSHes for requests which shared43* PREFLUSH.44*45* C3. The second condition is ignored if there is a request which has46* waited longer than FLUSH_PENDING_TIMEOUT. This is to avoid47* starvation in the unlikely case where there are continuous stream of48* FUA (without PREFLUSH) requests.49*50* For devices which support FUA, it isn't clear whether C2 (and thus C3)51* is beneficial.52*53* Note that a sequenced PREFLUSH/FUA request with DATA is completed twice.54* Once while executing DATA and again after the whole sequence is55* complete. The first completion updates the contained bio but doesn't56* finish it so that the bio submitter is notified only after the whole57* sequence is complete. This is implemented by testing RQF_FLUSH_SEQ in58* req_bio_endio().59*60* The above peculiarity requires that each PREFLUSH/FUA request has only one61* bio attached to it, which is guaranteed as they aren't allowed to be62* merged in the usual way.63*/6465#include <linux/kernel.h>66#include <linux/module.h>67#include <linux/bio.h>68#include <linux/blkdev.h>69#include <linux/gfp.h>70#include <linux/part_stat.h>7172#include "blk.h"73#include "blk-mq.h"74#include "blk-mq-sched.h"7576/* PREFLUSH/FUA sequences */77enum {78REQ_FSEQ_PREFLUSH = (1 << 0), /* pre-flushing in progress */79REQ_FSEQ_DATA = (1 << 1), /* data write in progress */80REQ_FSEQ_POSTFLUSH = (1 << 2), /* post-flushing in progress */81REQ_FSEQ_DONE = (1 << 3),8283REQ_FSEQ_ACTIONS = REQ_FSEQ_PREFLUSH | REQ_FSEQ_DATA |84REQ_FSEQ_POSTFLUSH,8586/*87* If flush has been pending longer than the following timeout,88* it's issued even if flush_data requests are still in flight.89*/90FLUSH_PENDING_TIMEOUT = 5 * HZ,91};9293static void blk_kick_flush(struct request_queue *q,94struct blk_flush_queue *fq, blk_opf_t flags);9596static inline struct blk_flush_queue *97blk_get_flush_queue(struct blk_mq_ctx *ctx)98{99return blk_mq_map_queue(REQ_OP_FLUSH, ctx)->fq;100}101102static unsigned int blk_flush_cur_seq(struct request *rq)103{104return 1 << ffz(rq->flush.seq);105}106107static void blk_flush_restore_request(struct request *rq)108{109/*110* After flush data completion, @rq->bio is %NULL but we need to111* complete the bio again. @rq->biotail is guaranteed to equal the112* original @rq->bio. Restore it.113*/114rq->bio = rq->biotail;115if (rq->bio)116rq->__sector = rq->bio->bi_iter.bi_sector;117118/* make @rq a normal request */119rq->rq_flags &= ~RQF_FLUSH_SEQ;120rq->end_io = rq->flush.saved_end_io;121}122123static void blk_account_io_flush(struct request *rq)124{125struct block_device *part = rq->q->disk->part0;126127part_stat_lock();128part_stat_inc(part, ios[STAT_FLUSH]);129part_stat_add(part, nsecs[STAT_FLUSH],130blk_time_get_ns() - rq->start_time_ns);131part_stat_unlock();132}133134/**135* blk_flush_complete_seq - complete flush sequence136* @rq: PREFLUSH/FUA request being sequenced137* @fq: flush queue138* @seq: sequences to complete (mask of %REQ_FSEQ_*, can be zero)139* @error: whether an error occurred140*141* @rq just completed @seq part of its flush sequence, record the142* completion and trigger the next step.143*144* CONTEXT:145* spin_lock_irq(fq->mq_flush_lock)146*/147static void blk_flush_complete_seq(struct request *rq,148struct blk_flush_queue *fq,149unsigned int seq, blk_status_t error)150{151struct request_queue *q = rq->q;152struct list_head *pending = &fq->flush_queue[fq->flush_pending_idx];153blk_opf_t cmd_flags;154155BUG_ON(rq->flush.seq & seq);156rq->flush.seq |= seq;157cmd_flags = rq->cmd_flags;158159if (likely(!error))160seq = blk_flush_cur_seq(rq);161else162seq = REQ_FSEQ_DONE;163164switch (seq) {165case REQ_FSEQ_PREFLUSH:166case REQ_FSEQ_POSTFLUSH:167/* queue for flush */168if (list_empty(pending))169fq->flush_pending_since = jiffies;170list_add_tail(&rq->queuelist, pending);171break;172173case REQ_FSEQ_DATA:174fq->flush_data_in_flight++;175spin_lock(&q->requeue_lock);176list_move(&rq->queuelist, &q->requeue_list);177spin_unlock(&q->requeue_lock);178blk_mq_kick_requeue_list(q);179break;180181case REQ_FSEQ_DONE:182/*183* @rq was previously adjusted by blk_insert_flush() for184* flush sequencing and may already have gone through the185* flush data request completion path. Restore @rq for186* normal completion and end it.187*/188list_del_init(&rq->queuelist);189blk_flush_restore_request(rq);190blk_mq_end_request(rq, error);191break;192193default:194BUG();195}196197blk_kick_flush(q, fq, cmd_flags);198}199200static enum rq_end_io_ret flush_end_io(struct request *flush_rq,201blk_status_t error)202{203struct request_queue *q = flush_rq->q;204struct list_head *running;205struct request *rq, *n;206unsigned long flags = 0;207struct blk_flush_queue *fq = blk_get_flush_queue(flush_rq->mq_ctx);208209/* release the tag's ownership to the req cloned from */210spin_lock_irqsave(&fq->mq_flush_lock, flags);211212if (!req_ref_put_and_test(flush_rq)) {213fq->rq_status = error;214spin_unlock_irqrestore(&fq->mq_flush_lock, flags);215return RQ_END_IO_NONE;216}217218blk_account_io_flush(flush_rq);219/*220* Flush request has to be marked as IDLE when it is really ended221* because its .end_io() is called from timeout code path too for222* avoiding use-after-free.223*/224WRITE_ONCE(flush_rq->state, MQ_RQ_IDLE);225if (fq->rq_status != BLK_STS_OK) {226error = fq->rq_status;227fq->rq_status = BLK_STS_OK;228}229230if (!q->elevator) {231flush_rq->tag = BLK_MQ_NO_TAG;232} else {233blk_mq_put_driver_tag(flush_rq);234flush_rq->internal_tag = BLK_MQ_NO_TAG;235}236237running = &fq->flush_queue[fq->flush_running_idx];238BUG_ON(fq->flush_pending_idx == fq->flush_running_idx);239240/* account completion of the flush request */241fq->flush_running_idx ^= 1;242243/* and push the waiting requests to the next stage */244list_for_each_entry_safe(rq, n, running, queuelist) {245unsigned int seq = blk_flush_cur_seq(rq);246247BUG_ON(seq != REQ_FSEQ_PREFLUSH && seq != REQ_FSEQ_POSTFLUSH);248list_del_init(&rq->queuelist);249blk_flush_complete_seq(rq, fq, seq, error);250}251252spin_unlock_irqrestore(&fq->mq_flush_lock, flags);253return RQ_END_IO_NONE;254}255256bool is_flush_rq(struct request *rq)257{258return rq->end_io == flush_end_io;259}260261/**262* blk_kick_flush - consider issuing flush request263* @q: request_queue being kicked264* @fq: flush queue265* @flags: cmd_flags of the original request266*267* Flush related states of @q have changed, consider issuing flush request.268* Please read the comment at the top of this file for more info.269*270* CONTEXT:271* spin_lock_irq(fq->mq_flush_lock)272*273*/274static void blk_kick_flush(struct request_queue *q, struct blk_flush_queue *fq,275blk_opf_t flags)276{277struct list_head *pending = &fq->flush_queue[fq->flush_pending_idx];278struct request *first_rq =279list_first_entry(pending, struct request, queuelist);280struct request *flush_rq = fq->flush_rq;281282/* C1 described at the top of this file */283if (fq->flush_pending_idx != fq->flush_running_idx || list_empty(pending))284return;285286/* C2 and C3 */287if (fq->flush_data_in_flight &&288time_before(jiffies,289fq->flush_pending_since + FLUSH_PENDING_TIMEOUT))290return;291292/*293* Issue flush and toggle pending_idx. This makes pending_idx294* different from running_idx, which means flush is in flight.295*/296fq->flush_pending_idx ^= 1;297298blk_rq_init(q, flush_rq);299300/*301* In case of none scheduler, borrow tag from the first request302* since they can't be in flight at the same time. And acquire303* the tag's ownership for flush req.304*305* In case of IO scheduler, flush rq need to borrow scheduler tag306* just for cheating put/get driver tag.307*/308flush_rq->mq_ctx = first_rq->mq_ctx;309flush_rq->mq_hctx = first_rq->mq_hctx;310311if (!q->elevator)312flush_rq->tag = first_rq->tag;313else314flush_rq->internal_tag = first_rq->internal_tag;315316flush_rq->cmd_flags = REQ_OP_FLUSH | REQ_PREFLUSH;317flush_rq->cmd_flags |= (flags & REQ_DRV) | (flags & REQ_FAILFAST_MASK);318flush_rq->rq_flags |= RQF_FLUSH_SEQ;319flush_rq->end_io = flush_end_io;320/*321* Order WRITE ->end_io and WRITE rq->ref, and its pair is the one322* implied in refcount_inc_not_zero() called from323* blk_mq_find_and_get_req(), which orders WRITE/READ flush_rq->ref324* and READ flush_rq->end_io325*/326smp_wmb();327req_ref_set(flush_rq, 1);328329spin_lock(&q->requeue_lock);330list_add_tail(&flush_rq->queuelist, &q->flush_list);331spin_unlock(&q->requeue_lock);332333blk_mq_kick_requeue_list(q);334}335336static enum rq_end_io_ret mq_flush_data_end_io(struct request *rq,337blk_status_t error)338{339struct request_queue *q = rq->q;340struct blk_mq_hw_ctx *hctx = rq->mq_hctx;341struct blk_mq_ctx *ctx = rq->mq_ctx;342unsigned long flags;343struct blk_flush_queue *fq = blk_get_flush_queue(ctx);344345if (q->elevator) {346WARN_ON(rq->tag < 0);347blk_mq_put_driver_tag(rq);348}349350/*351* After populating an empty queue, kick it to avoid stall. Read352* the comment in flush_end_io().353*/354spin_lock_irqsave(&fq->mq_flush_lock, flags);355fq->flush_data_in_flight--;356/*357* May have been corrupted by rq->rq_next reuse, we need to358* re-initialize rq->queuelist before reusing it here.359*/360INIT_LIST_HEAD(&rq->queuelist);361blk_flush_complete_seq(rq, fq, REQ_FSEQ_DATA, error);362spin_unlock_irqrestore(&fq->mq_flush_lock, flags);363364blk_mq_sched_restart(hctx);365return RQ_END_IO_NONE;366}367368static void blk_rq_init_flush(struct request *rq)369{370rq->flush.seq = 0;371rq->rq_flags |= RQF_FLUSH_SEQ;372rq->flush.saved_end_io = rq->end_io; /* Usually NULL */373rq->end_io = mq_flush_data_end_io;374}375376/*377* Insert a PREFLUSH/FUA request into the flush state machine.378* Returns true if the request has been consumed by the flush state machine,379* or false if the caller should continue to process it.380*/381bool blk_insert_flush(struct request *rq)382{383struct request_queue *q = rq->q;384struct blk_flush_queue *fq = blk_get_flush_queue(rq->mq_ctx);385bool supports_fua = q->limits.features & BLK_FEAT_FUA;386unsigned int policy = 0;387388/* FLUSH/FUA request must never be merged */389WARN_ON_ONCE(rq->bio != rq->biotail);390391if (blk_rq_sectors(rq))392policy |= REQ_FSEQ_DATA;393394/*395* Check which flushes we need to sequence for this operation.396*/397if (blk_queue_write_cache(q)) {398if (rq->cmd_flags & REQ_PREFLUSH)399policy |= REQ_FSEQ_PREFLUSH;400if ((rq->cmd_flags & REQ_FUA) && !supports_fua)401policy |= REQ_FSEQ_POSTFLUSH;402}403404/*405* @policy now records what operations need to be done. Adjust406* REQ_PREFLUSH and FUA for the driver.407*/408rq->cmd_flags &= ~REQ_PREFLUSH;409if (!supports_fua)410rq->cmd_flags &= ~REQ_FUA;411412/*413* REQ_PREFLUSH|REQ_FUA implies REQ_SYNC, so if we clear any414* of those flags, we have to set REQ_SYNC to avoid skewing415* the request accounting.416*/417rq->cmd_flags |= REQ_SYNC;418419switch (policy) {420case 0:421/*422* An empty flush handed down from a stacking driver may423* translate into nothing if the underlying device does not424* advertise a write-back cache. In this case, simply425* complete the request.426*/427blk_mq_end_request(rq, 0);428return true;429case REQ_FSEQ_DATA:430/*431* If there's data, but no flush is necessary, the request can432* be processed directly without going through flush machinery.433* Queue for normal execution.434*/435return false;436case REQ_FSEQ_DATA | REQ_FSEQ_POSTFLUSH:437/*438* Initialize the flush fields and completion handler to trigger439* the post flush, and then just pass the command on.440*/441blk_rq_init_flush(rq);442rq->flush.seq |= REQ_FSEQ_PREFLUSH;443spin_lock_irq(&fq->mq_flush_lock);444fq->flush_data_in_flight++;445spin_unlock_irq(&fq->mq_flush_lock);446return false;447default:448/*449* Mark the request as part of a flush sequence and submit it450* for further processing to the flush state machine.451*/452blk_rq_init_flush(rq);453spin_lock_irq(&fq->mq_flush_lock);454blk_flush_complete_seq(rq, fq, REQ_FSEQ_ACTIONS & ~policy, 0);455spin_unlock_irq(&fq->mq_flush_lock);456return true;457}458}459460/**461* blkdev_issue_flush - queue a flush462* @bdev: blockdev to issue flush for463*464* Description:465* Issue a flush for the block device in question.466*/467int blkdev_issue_flush(struct block_device *bdev)468{469struct bio bio;470471bio_init(&bio, bdev, NULL, 0, REQ_OP_WRITE | REQ_PREFLUSH);472return submit_bio_wait(&bio);473}474EXPORT_SYMBOL(blkdev_issue_flush);475476struct blk_flush_queue *blk_alloc_flush_queue(int node, int cmd_size,477gfp_t flags)478{479struct blk_flush_queue *fq;480int rq_sz = sizeof(struct request);481482fq = kzalloc_node(sizeof(*fq), flags, node);483if (!fq)484goto fail;485486spin_lock_init(&fq->mq_flush_lock);487488rq_sz = round_up(rq_sz + cmd_size, cache_line_size());489fq->flush_rq = kzalloc_node(rq_sz, flags, node);490if (!fq->flush_rq)491goto fail_rq;492493INIT_LIST_HEAD(&fq->flush_queue[0]);494INIT_LIST_HEAD(&fq->flush_queue[1]);495496return fq;497498fail_rq:499kfree(fq);500fail:501return NULL;502}503504void blk_free_flush_queue(struct blk_flush_queue *fq)505{506/* bio based request queue hasn't flush queue */507if (!fq)508return;509510kfree(fq->flush_rq);511kfree(fq);512}513514/*515* Allow driver to set its own lock class to fq->mq_flush_lock for516* avoiding lockdep complaint.517*518* flush_end_io() may be called recursively from some driver, such as519* nvme-loop, so lockdep may complain 'possible recursive locking' because520* all 'struct blk_flush_queue' instance share same mq_flush_lock lock class521* key. We need to assign different lock class for these driver's522* fq->mq_flush_lock for avoiding the lockdep warning.523*524* Use dynamically allocated lock class key for each 'blk_flush_queue'525* instance is over-kill, and more worse it introduces horrible boot delay526* issue because synchronize_rcu() is implied in lockdep_unregister_key which527* is called for each hctx release. SCSI probing may synchronously create and528* destroy lots of MQ request_queues for non-existent devices, and some robot529* test kernel always enable lockdep option. It is observed that more than half530* an hour is taken during SCSI MQ probe with per-fq lock class.531*/532void blk_mq_hctx_set_fq_lock_class(struct blk_mq_hw_ctx *hctx,533struct lock_class_key *key)534{535lockdep_set_class(&hctx->fq->mq_flush_lock, key);536}537EXPORT_SYMBOL_GPL(blk_mq_hctx_set_fq_lock_class);538539540