xref: /openbmc/linux/drivers/scsi/sd_zbc.c (revision 79e790ff)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * SCSI Zoned Block commands
4  *
5  * Copyright (C) 2014-2015 SUSE Linux GmbH
6  * Written by: Hannes Reinecke <hare@suse.de>
7  * Modified by: Damien Le Moal <damien.lemoal@hgst.com>
8  * Modified by: Shaun Tancheff <shaun.tancheff@seagate.com>
9  */
10 
11 #include <linux/blkdev.h>
12 #include <linux/vmalloc.h>
13 #include <linux/sched/mm.h>
14 #include <linux/mutex.h>
15 
16 #include <asm/unaligned.h>
17 
18 #include <scsi/scsi.h>
19 #include <scsi/scsi_cmnd.h>
20 
21 #include "sd.h"
22 
23 static unsigned int sd_zbc_get_zone_wp_offset(struct blk_zone *zone)
24 {
25 	if (zone->type == ZBC_ZONE_TYPE_CONV)
26 		return 0;
27 
28 	switch (zone->cond) {
29 	case BLK_ZONE_COND_IMP_OPEN:
30 	case BLK_ZONE_COND_EXP_OPEN:
31 	case BLK_ZONE_COND_CLOSED:
32 		return zone->wp - zone->start;
33 	case BLK_ZONE_COND_FULL:
34 		return zone->len;
35 	case BLK_ZONE_COND_EMPTY:
36 	case BLK_ZONE_COND_OFFLINE:
37 	case BLK_ZONE_COND_READONLY:
38 	default:
39 		/*
40 		 * Offline and read-only zones do not have a valid
41 		 * write pointer. Use 0 as for an empty zone.
42 		 */
43 		return 0;
44 	}
45 }
46 
47 static int sd_zbc_parse_report(struct scsi_disk *sdkp, u8 *buf,
48 			       unsigned int idx, report_zones_cb cb, void *data)
49 {
50 	struct scsi_device *sdp = sdkp->device;
51 	struct blk_zone zone = { 0 };
52 	int ret;
53 
54 	zone.type = buf[0] & 0x0f;
55 	zone.cond = (buf[1] >> 4) & 0xf;
56 	if (buf[1] & 0x01)
57 		zone.reset = 1;
58 	if (buf[1] & 0x02)
59 		zone.non_seq = 1;
60 
61 	zone.len = logical_to_sectors(sdp, get_unaligned_be64(&buf[8]));
62 	zone.capacity = zone.len;
63 	zone.start = logical_to_sectors(sdp, get_unaligned_be64(&buf[16]));
64 	zone.wp = logical_to_sectors(sdp, get_unaligned_be64(&buf[24]));
65 	if (zone.type != ZBC_ZONE_TYPE_CONV &&
66 	    zone.cond == ZBC_ZONE_COND_FULL)
67 		zone.wp = zone.start + zone.len;
68 
69 	ret = cb(&zone, idx, data);
70 	if (ret)
71 		return ret;
72 
73 	if (sdkp->rev_wp_offset)
74 		sdkp->rev_wp_offset[idx] = sd_zbc_get_zone_wp_offset(&zone);
75 
76 	return 0;
77 }
78 
79 /**
80  * sd_zbc_do_report_zones - Issue a REPORT ZONES scsi command.
81  * @sdkp: The target disk
82  * @buf: vmalloc-ed buffer to use for the reply
83  * @buflen: the buffer size
84  * @lba: Start LBA of the report
85  * @partial: Do partial report
86  *
87  * For internal use during device validation.
88  * Using partial=true can significantly speed up execution of a report zones
89  * command because the disk does not have to count all possible report matching
90  * zones and will only report the count of zones fitting in the command reply
91  * buffer.
92  */
93 static int sd_zbc_do_report_zones(struct scsi_disk *sdkp, unsigned char *buf,
94 				  unsigned int buflen, sector_t lba,
95 				  bool partial)
96 {
97 	struct scsi_device *sdp = sdkp->device;
98 	const int timeout = sdp->request_queue->rq_timeout;
99 	struct scsi_sense_hdr sshdr;
100 	unsigned char cmd[16];
101 	unsigned int rep_len;
102 	int result;
103 
104 	memset(cmd, 0, 16);
105 	cmd[0] = ZBC_IN;
106 	cmd[1] = ZI_REPORT_ZONES;
107 	put_unaligned_be64(lba, &cmd[2]);
108 	put_unaligned_be32(buflen, &cmd[10]);
109 	if (partial)
110 		cmd[14] = ZBC_REPORT_ZONE_PARTIAL;
111 
112 	result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
113 				  buf, buflen, &sshdr,
114 				  timeout, SD_MAX_RETRIES, NULL);
115 	if (result) {
116 		sd_printk(KERN_ERR, sdkp,
117 			  "REPORT ZONES start lba %llu failed\n", lba);
118 		sd_print_result(sdkp, "REPORT ZONES", result);
119 		if (driver_byte(result) == DRIVER_SENSE &&
120 		    scsi_sense_valid(&sshdr))
121 			sd_print_sense_hdr(sdkp, &sshdr);
122 		return -EIO;
123 	}
124 
125 	rep_len = get_unaligned_be32(&buf[0]);
126 	if (rep_len < 64) {
127 		sd_printk(KERN_ERR, sdkp,
128 			  "REPORT ZONES report invalid length %u\n",
129 			  rep_len);
130 		return -EIO;
131 	}
132 
133 	return 0;
134 }
135 
136 /**
137  * sd_zbc_alloc_report_buffer() - Allocate a buffer for report zones reply.
138  * @sdkp: The target disk
139  * @nr_zones: Maximum number of zones to report
140  * @buflen: Size of the buffer allocated
141  *
142  * Try to allocate a reply buffer for the number of requested zones.
143  * The size of the buffer allocated may be smaller than requested to
144  * satify the device constraint (max_hw_sectors, max_segments, etc).
145  *
146  * Return the address of the allocated buffer and update @buflen with
147  * the size of the allocated buffer.
148  */
149 static void *sd_zbc_alloc_report_buffer(struct scsi_disk *sdkp,
150 					unsigned int nr_zones, size_t *buflen)
151 {
152 	struct request_queue *q = sdkp->disk->queue;
153 	size_t bufsize;
154 	void *buf;
155 
156 	/*
157 	 * Report zone buffer size should be at most 64B times the number of
158 	 * zones requested plus the 64B reply header, but should be at least
159 	 * SECTOR_SIZE for ATA devices.
160 	 * Make sure that this size does not exceed the hardware capabilities.
161 	 * Furthermore, since the report zone command cannot be split, make
162 	 * sure that the allocated buffer can always be mapped by limiting the
163 	 * number of pages allocated to the HBA max segments limit.
164 	 */
165 	nr_zones = min(nr_zones, sdkp->nr_zones);
166 	bufsize = roundup((nr_zones + 1) * 64, SECTOR_SIZE);
167 	bufsize = min_t(size_t, bufsize,
168 			queue_max_hw_sectors(q) << SECTOR_SHIFT);
169 	bufsize = min_t(size_t, bufsize, queue_max_segments(q) << PAGE_SHIFT);
170 
171 	while (bufsize >= SECTOR_SIZE) {
172 		buf = __vmalloc(bufsize,
173 				GFP_KERNEL | __GFP_ZERO | __GFP_NORETRY);
174 		if (buf) {
175 			*buflen = bufsize;
176 			return buf;
177 		}
178 		bufsize >>= 1;
179 	}
180 
181 	return NULL;
182 }
183 
184 /**
185  * sd_zbc_zone_sectors - Get the device zone size in number of 512B sectors.
186  * @sdkp: The target disk
187  */
188 static inline sector_t sd_zbc_zone_sectors(struct scsi_disk *sdkp)
189 {
190 	return logical_to_sectors(sdkp->device, sdkp->zone_blocks);
191 }
192 
193 int sd_zbc_report_zones(struct gendisk *disk, sector_t sector,
194 			unsigned int nr_zones, report_zones_cb cb, void *data)
195 {
196 	struct scsi_disk *sdkp = scsi_disk(disk);
197 	sector_t capacity = logical_to_sectors(sdkp->device, sdkp->capacity);
198 	unsigned int nr, i;
199 	unsigned char *buf;
200 	size_t offset, buflen = 0;
201 	int zone_idx = 0;
202 	int ret;
203 
204 	if (!sd_is_zoned(sdkp))
205 		/* Not a zoned device */
206 		return -EOPNOTSUPP;
207 
208 	if (!capacity)
209 		/* Device gone or invalid */
210 		return -ENODEV;
211 
212 	buf = sd_zbc_alloc_report_buffer(sdkp, nr_zones, &buflen);
213 	if (!buf)
214 		return -ENOMEM;
215 
216 	while (zone_idx < nr_zones && sector < capacity) {
217 		ret = sd_zbc_do_report_zones(sdkp, buf, buflen,
218 				sectors_to_logical(sdkp->device, sector), true);
219 		if (ret)
220 			goto out;
221 
222 		offset = 0;
223 		nr = min(nr_zones, get_unaligned_be32(&buf[0]) / 64);
224 		if (!nr)
225 			break;
226 
227 		for (i = 0; i < nr && zone_idx < nr_zones; i++) {
228 			offset += 64;
229 			ret = sd_zbc_parse_report(sdkp, buf + offset, zone_idx,
230 						  cb, data);
231 			if (ret)
232 				goto out;
233 			zone_idx++;
234 		}
235 
236 		sector += sd_zbc_zone_sectors(sdkp) * i;
237 	}
238 
239 	ret = zone_idx;
240 out:
241 	kvfree(buf);
242 	return ret;
243 }
244 
245 static blk_status_t sd_zbc_cmnd_checks(struct scsi_cmnd *cmd)
246 {
247 	struct request *rq = cmd->request;
248 	struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
249 	sector_t sector = blk_rq_pos(rq);
250 
251 	if (!sd_is_zoned(sdkp))
252 		/* Not a zoned device */
253 		return BLK_STS_IOERR;
254 
255 	if (sdkp->device->changed)
256 		return BLK_STS_IOERR;
257 
258 	if (sector & (sd_zbc_zone_sectors(sdkp) - 1))
259 		/* Unaligned request */
260 		return BLK_STS_IOERR;
261 
262 	return BLK_STS_OK;
263 }
264 
265 #define SD_ZBC_INVALID_WP_OFST	(~0u)
266 #define SD_ZBC_UPDATING_WP_OFST	(SD_ZBC_INVALID_WP_OFST - 1)
267 
268 static int sd_zbc_update_wp_offset_cb(struct blk_zone *zone, unsigned int idx,
269 				    void *data)
270 {
271 	struct scsi_disk *sdkp = data;
272 
273 	lockdep_assert_held(&sdkp->zones_wp_offset_lock);
274 
275 	sdkp->zones_wp_offset[idx] = sd_zbc_get_zone_wp_offset(zone);
276 
277 	return 0;
278 }
279 
280 static void sd_zbc_update_wp_offset_workfn(struct work_struct *work)
281 {
282 	struct scsi_disk *sdkp;
283 	unsigned long flags;
284 	unsigned int zno;
285 	int ret;
286 
287 	sdkp = container_of(work, struct scsi_disk, zone_wp_offset_work);
288 
289 	spin_lock_irqsave(&sdkp->zones_wp_offset_lock, flags);
290 	for (zno = 0; zno < sdkp->nr_zones; zno++) {
291 		if (sdkp->zones_wp_offset[zno] != SD_ZBC_UPDATING_WP_OFST)
292 			continue;
293 
294 		spin_unlock_irqrestore(&sdkp->zones_wp_offset_lock, flags);
295 		ret = sd_zbc_do_report_zones(sdkp, sdkp->zone_wp_update_buf,
296 					     SD_BUF_SIZE,
297 					     zno * sdkp->zone_blocks, true);
298 		spin_lock_irqsave(&sdkp->zones_wp_offset_lock, flags);
299 		if (!ret)
300 			sd_zbc_parse_report(sdkp, sdkp->zone_wp_update_buf + 64,
301 					    zno, sd_zbc_update_wp_offset_cb,
302 					    sdkp);
303 	}
304 	spin_unlock_irqrestore(&sdkp->zones_wp_offset_lock, flags);
305 
306 	scsi_device_put(sdkp->device);
307 }
308 
309 /**
310  * sd_zbc_prepare_zone_append() - Prepare an emulated ZONE_APPEND command.
311  * @cmd: the command to setup
312  * @lba: the LBA to patch
313  * @nr_blocks: the number of LBAs to be written
314  *
315  * Called from sd_setup_read_write_cmnd() for REQ_OP_ZONE_APPEND.
316  * @sd_zbc_prepare_zone_append() handles the necessary zone wrote locking and
317  * patching of the lba for an emulated ZONE_APPEND command.
318  *
319  * In case the cached write pointer offset is %SD_ZBC_INVALID_WP_OFST it will
320  * schedule a REPORT ZONES command and return BLK_STS_IOERR.
321  */
322 blk_status_t sd_zbc_prepare_zone_append(struct scsi_cmnd *cmd, sector_t *lba,
323 					unsigned int nr_blocks)
324 {
325 	struct request *rq = cmd->request;
326 	struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
327 	unsigned int wp_offset, zno = blk_rq_zone_no(rq);
328 	unsigned long flags;
329 	blk_status_t ret;
330 
331 	ret = sd_zbc_cmnd_checks(cmd);
332 	if (ret != BLK_STS_OK)
333 		return ret;
334 
335 	if (!blk_rq_zone_is_seq(rq))
336 		return BLK_STS_IOERR;
337 
338 	/* Unlock of the write lock will happen in sd_zbc_complete() */
339 	if (!blk_req_zone_write_trylock(rq))
340 		return BLK_STS_ZONE_RESOURCE;
341 
342 	spin_lock_irqsave(&sdkp->zones_wp_offset_lock, flags);
343 	wp_offset = sdkp->zones_wp_offset[zno];
344 	switch (wp_offset) {
345 	case SD_ZBC_INVALID_WP_OFST:
346 		/*
347 		 * We are about to schedule work to update a zone write pointer
348 		 * offset, which will cause the zone append command to be
349 		 * requeued. So make sure that the scsi device does not go away
350 		 * while the work is being processed.
351 		 */
352 		if (scsi_device_get(sdkp->device)) {
353 			ret = BLK_STS_IOERR;
354 			break;
355 		}
356 		sdkp->zones_wp_offset[zno] = SD_ZBC_UPDATING_WP_OFST;
357 		schedule_work(&sdkp->zone_wp_offset_work);
358 		fallthrough;
359 	case SD_ZBC_UPDATING_WP_OFST:
360 		ret = BLK_STS_DEV_RESOURCE;
361 		break;
362 	default:
363 		wp_offset = sectors_to_logical(sdkp->device, wp_offset);
364 		if (wp_offset + nr_blocks > sdkp->zone_blocks) {
365 			ret = BLK_STS_IOERR;
366 			break;
367 		}
368 
369 		*lba += wp_offset;
370 	}
371 	spin_unlock_irqrestore(&sdkp->zones_wp_offset_lock, flags);
372 	if (ret)
373 		blk_req_zone_write_unlock(rq);
374 	return ret;
375 }
376 
377 /**
378  * sd_zbc_setup_zone_mgmt_cmnd - Prepare a zone ZBC_OUT command. The operations
379  *			can be RESET WRITE POINTER, OPEN, CLOSE or FINISH.
380  * @cmd: the command to setup
381  * @op: Operation to be performed
382  * @all: All zones control
383  *
384  * Called from sd_init_command() for REQ_OP_ZONE_RESET, REQ_OP_ZONE_RESET_ALL,
385  * REQ_OP_ZONE_OPEN, REQ_OP_ZONE_CLOSE or REQ_OP_ZONE_FINISH requests.
386  */
387 blk_status_t sd_zbc_setup_zone_mgmt_cmnd(struct scsi_cmnd *cmd,
388 					 unsigned char op, bool all)
389 {
390 	struct request *rq = cmd->request;
391 	sector_t sector = blk_rq_pos(rq);
392 	struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
393 	sector_t block = sectors_to_logical(sdkp->device, sector);
394 	blk_status_t ret;
395 
396 	ret = sd_zbc_cmnd_checks(cmd);
397 	if (ret != BLK_STS_OK)
398 		return ret;
399 
400 	cmd->cmd_len = 16;
401 	memset(cmd->cmnd, 0, cmd->cmd_len);
402 	cmd->cmnd[0] = ZBC_OUT;
403 	cmd->cmnd[1] = op;
404 	if (all)
405 		cmd->cmnd[14] = 0x1;
406 	else
407 		put_unaligned_be64(block, &cmd->cmnd[2]);
408 
409 	rq->timeout = SD_TIMEOUT;
410 	cmd->sc_data_direction = DMA_NONE;
411 	cmd->transfersize = 0;
412 	cmd->allowed = 0;
413 
414 	return BLK_STS_OK;
415 }
416 
417 static bool sd_zbc_need_zone_wp_update(struct request *rq)
418 {
419 	switch (req_op(rq)) {
420 	case REQ_OP_ZONE_APPEND:
421 	case REQ_OP_ZONE_FINISH:
422 	case REQ_OP_ZONE_RESET:
423 	case REQ_OP_ZONE_RESET_ALL:
424 		return true;
425 	case REQ_OP_WRITE:
426 	case REQ_OP_WRITE_ZEROES:
427 	case REQ_OP_WRITE_SAME:
428 		return blk_rq_zone_is_seq(rq);
429 	default:
430 		return false;
431 	}
432 }
433 
434 /**
435  * sd_zbc_zone_wp_update - Update cached zone write pointer upon cmd completion
436  * @cmd: Completed command
437  * @good_bytes: Command reply bytes
438  *
439  * Called from sd_zbc_complete() to handle the update of the cached zone write
440  * pointer value in case an update is needed.
441  */
442 static unsigned int sd_zbc_zone_wp_update(struct scsi_cmnd *cmd,
443 					  unsigned int good_bytes)
444 {
445 	int result = cmd->result;
446 	struct request *rq = cmd->request;
447 	struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
448 	unsigned int zno = blk_rq_zone_no(rq);
449 	enum req_opf op = req_op(rq);
450 	unsigned long flags;
451 
452 	/*
453 	 * If we got an error for a command that needs updating the write
454 	 * pointer offset cache, we must mark the zone wp offset entry as
455 	 * invalid to force an update from disk the next time a zone append
456 	 * command is issued.
457 	 */
458 	spin_lock_irqsave(&sdkp->zones_wp_offset_lock, flags);
459 
460 	if (result && op != REQ_OP_ZONE_RESET_ALL) {
461 		if (op == REQ_OP_ZONE_APPEND) {
462 			/* Force complete completion (no retry) */
463 			good_bytes = 0;
464 			scsi_set_resid(cmd, blk_rq_bytes(rq));
465 		}
466 
467 		/*
468 		 * Force an update of the zone write pointer offset on
469 		 * the next zone append access.
470 		 */
471 		if (sdkp->zones_wp_offset[zno] != SD_ZBC_UPDATING_WP_OFST)
472 			sdkp->zones_wp_offset[zno] = SD_ZBC_INVALID_WP_OFST;
473 		goto unlock_wp_offset;
474 	}
475 
476 	switch (op) {
477 	case REQ_OP_ZONE_APPEND:
478 		rq->__sector += sdkp->zones_wp_offset[zno];
479 		fallthrough;
480 	case REQ_OP_WRITE_ZEROES:
481 	case REQ_OP_WRITE_SAME:
482 	case REQ_OP_WRITE:
483 		if (sdkp->zones_wp_offset[zno] < sd_zbc_zone_sectors(sdkp))
484 			sdkp->zones_wp_offset[zno] +=
485 						good_bytes >> SECTOR_SHIFT;
486 		break;
487 	case REQ_OP_ZONE_RESET:
488 		sdkp->zones_wp_offset[zno] = 0;
489 		break;
490 	case REQ_OP_ZONE_FINISH:
491 		sdkp->zones_wp_offset[zno] = sd_zbc_zone_sectors(sdkp);
492 		break;
493 	case REQ_OP_ZONE_RESET_ALL:
494 		memset(sdkp->zones_wp_offset, 0,
495 		       sdkp->nr_zones * sizeof(unsigned int));
496 		break;
497 	default:
498 		break;
499 	}
500 
501 unlock_wp_offset:
502 	spin_unlock_irqrestore(&sdkp->zones_wp_offset_lock, flags);
503 
504 	return good_bytes;
505 }
506 
507 /**
508  * sd_zbc_complete - ZBC command post processing.
509  * @cmd: Completed command
510  * @good_bytes: Command reply bytes
511  * @sshdr: command sense header
512  *
513  * Called from sd_done() to handle zone commands errors and updates to the
514  * device queue zone write pointer offset cahce.
515  */
516 unsigned int sd_zbc_complete(struct scsi_cmnd *cmd, unsigned int good_bytes,
517 		     struct scsi_sense_hdr *sshdr)
518 {
519 	int result = cmd->result;
520 	struct request *rq = cmd->request;
521 
522 	if (op_is_zone_mgmt(req_op(rq)) &&
523 	    result &&
524 	    sshdr->sense_key == ILLEGAL_REQUEST &&
525 	    sshdr->asc == 0x24) {
526 		/*
527 		 * INVALID FIELD IN CDB error: a zone management command was
528 		 * attempted on a conventional zone. Nothing to worry about,
529 		 * so be quiet about the error.
530 		 */
531 		rq->rq_flags |= RQF_QUIET;
532 	} else if (sd_zbc_need_zone_wp_update(rq))
533 		good_bytes = sd_zbc_zone_wp_update(cmd, good_bytes);
534 
535 	if (req_op(rq) == REQ_OP_ZONE_APPEND)
536 		blk_req_zone_write_unlock(rq);
537 
538 	return good_bytes;
539 }
540 
541 /**
542  * sd_zbc_check_zoned_characteristics - Check zoned block device characteristics
543  * @sdkp: Target disk
544  * @buf: Buffer where to store the VPD page data
545  *
546  * Read VPD page B6, get information and check that reads are unconstrained.
547  */
548 static int sd_zbc_check_zoned_characteristics(struct scsi_disk *sdkp,
549 					      unsigned char *buf)
550 {
551 
552 	if (scsi_get_vpd_page(sdkp->device, 0xb6, buf, 64)) {
553 		sd_printk(KERN_NOTICE, sdkp,
554 			  "Read zoned characteristics VPD page failed\n");
555 		return -ENODEV;
556 	}
557 
558 	if (sdkp->device->type != TYPE_ZBC) {
559 		/* Host-aware */
560 		sdkp->urswrz = 1;
561 		sdkp->zones_optimal_open = get_unaligned_be32(&buf[8]);
562 		sdkp->zones_optimal_nonseq = get_unaligned_be32(&buf[12]);
563 		sdkp->zones_max_open = 0;
564 	} else {
565 		/* Host-managed */
566 		sdkp->urswrz = buf[4] & 1;
567 		sdkp->zones_optimal_open = 0;
568 		sdkp->zones_optimal_nonseq = 0;
569 		sdkp->zones_max_open = get_unaligned_be32(&buf[16]);
570 	}
571 
572 	/*
573 	 * Check for unconstrained reads: host-managed devices with
574 	 * constrained reads (drives failing read after write pointer)
575 	 * are not supported.
576 	 */
577 	if (!sdkp->urswrz) {
578 		if (sdkp->first_scan)
579 			sd_printk(KERN_NOTICE, sdkp,
580 			  "constrained reads devices are not supported\n");
581 		return -ENODEV;
582 	}
583 
584 	return 0;
585 }
586 
587 /**
588  * sd_zbc_check_capacity - Check the device capacity
589  * @sdkp: Target disk
590  * @buf: command buffer
591  * @zblocks: zone size in number of blocks
592  *
593  * Get the device zone size and check that the device capacity as reported
594  * by READ CAPACITY matches the max_lba value (plus one) of the report zones
595  * command reply for devices with RC_BASIS == 0.
596  *
597  * Returns 0 upon success or an error code upon failure.
598  */
599 static int sd_zbc_check_capacity(struct scsi_disk *sdkp, unsigned char *buf,
600 				 u32 *zblocks)
601 {
602 	u64 zone_blocks;
603 	sector_t max_lba;
604 	unsigned char *rec;
605 	int ret;
606 
607 	/* Do a report zone to get max_lba and the size of the first zone */
608 	ret = sd_zbc_do_report_zones(sdkp, buf, SD_BUF_SIZE, 0, false);
609 	if (ret)
610 		return ret;
611 
612 	if (sdkp->rc_basis == 0) {
613 		/* The max_lba field is the capacity of this device */
614 		max_lba = get_unaligned_be64(&buf[8]);
615 		if (sdkp->capacity != max_lba + 1) {
616 			if (sdkp->first_scan)
617 				sd_printk(KERN_WARNING, sdkp,
618 					"Changing capacity from %llu to max LBA+1 %llu\n",
619 					(unsigned long long)sdkp->capacity,
620 					(unsigned long long)max_lba + 1);
621 			sdkp->capacity = max_lba + 1;
622 		}
623 	}
624 
625 	/* Get the size of the first reported zone */
626 	rec = buf + 64;
627 	zone_blocks = get_unaligned_be64(&rec[8]);
628 	if (logical_to_sectors(sdkp->device, zone_blocks) > UINT_MAX) {
629 		if (sdkp->first_scan)
630 			sd_printk(KERN_NOTICE, sdkp,
631 				  "Zone size too large\n");
632 		return -EFBIG;
633 	}
634 
635 	*zblocks = zone_blocks;
636 
637 	return 0;
638 }
639 
640 static void sd_zbc_print_zones(struct scsi_disk *sdkp)
641 {
642 	if (!sd_is_zoned(sdkp) || !sdkp->capacity)
643 		return;
644 
645 	if (sdkp->capacity & (sdkp->zone_blocks - 1))
646 		sd_printk(KERN_NOTICE, sdkp,
647 			  "%u zones of %u logical blocks + 1 runt zone\n",
648 			  sdkp->nr_zones - 1,
649 			  sdkp->zone_blocks);
650 	else
651 		sd_printk(KERN_NOTICE, sdkp,
652 			  "%u zones of %u logical blocks\n",
653 			  sdkp->nr_zones,
654 			  sdkp->zone_blocks);
655 }
656 
657 static int sd_zbc_init_disk(struct scsi_disk *sdkp)
658 {
659 	sdkp->zones_wp_offset = NULL;
660 	spin_lock_init(&sdkp->zones_wp_offset_lock);
661 	sdkp->rev_wp_offset = NULL;
662 	mutex_init(&sdkp->rev_mutex);
663 	INIT_WORK(&sdkp->zone_wp_offset_work, sd_zbc_update_wp_offset_workfn);
664 	sdkp->zone_wp_update_buf = kzalloc(SD_BUF_SIZE, GFP_KERNEL);
665 	if (!sdkp->zone_wp_update_buf)
666 		return -ENOMEM;
667 
668 	return 0;
669 }
670 
671 static void sd_zbc_clear_zone_info(struct scsi_disk *sdkp)
672 {
673 	/* Serialize against revalidate zones */
674 	mutex_lock(&sdkp->rev_mutex);
675 
676 	kvfree(sdkp->zones_wp_offset);
677 	sdkp->zones_wp_offset = NULL;
678 	kfree(sdkp->zone_wp_update_buf);
679 	sdkp->zone_wp_update_buf = NULL;
680 
681 	sdkp->nr_zones = 0;
682 	sdkp->rev_nr_zones = 0;
683 	sdkp->zone_blocks = 0;
684 	sdkp->rev_zone_blocks = 0;
685 
686 	mutex_unlock(&sdkp->rev_mutex);
687 }
688 
689 void sd_zbc_release_disk(struct scsi_disk *sdkp)
690 {
691 	if (sd_is_zoned(sdkp))
692 		sd_zbc_clear_zone_info(sdkp);
693 }
694 
695 static void sd_zbc_revalidate_zones_cb(struct gendisk *disk)
696 {
697 	struct scsi_disk *sdkp = scsi_disk(disk);
698 
699 	swap(sdkp->zones_wp_offset, sdkp->rev_wp_offset);
700 }
701 
702 int sd_zbc_revalidate_zones(struct scsi_disk *sdkp)
703 {
704 	struct gendisk *disk = sdkp->disk;
705 	struct request_queue *q = disk->queue;
706 	u32 zone_blocks = sdkp->rev_zone_blocks;
707 	unsigned int nr_zones = sdkp->rev_nr_zones;
708 	u32 max_append;
709 	int ret = 0;
710 	unsigned int flags;
711 
712 	/*
713 	 * For all zoned disks, initialize zone append emulation data if not
714 	 * already done. This is necessary also for host-aware disks used as
715 	 * regular disks due to the presence of partitions as these partitions
716 	 * may be deleted and the disk zoned model changed back from
717 	 * BLK_ZONED_NONE to BLK_ZONED_HA.
718 	 */
719 	if (sd_is_zoned(sdkp) && !sdkp->zone_wp_update_buf) {
720 		ret = sd_zbc_init_disk(sdkp);
721 		if (ret)
722 			return ret;
723 	}
724 
725 	/*
726 	 * There is nothing to do for regular disks, including host-aware disks
727 	 * that have partitions.
728 	 */
729 	if (!blk_queue_is_zoned(q))
730 		return 0;
731 
732 	/*
733 	 * Make sure revalidate zones are serialized to ensure exclusive
734 	 * updates of the scsi disk data.
735 	 */
736 	mutex_lock(&sdkp->rev_mutex);
737 
738 	if (sdkp->zone_blocks == zone_blocks &&
739 	    sdkp->nr_zones == nr_zones &&
740 	    disk->queue->nr_zones == nr_zones)
741 		goto unlock;
742 
743 	flags = memalloc_noio_save();
744 	sdkp->zone_blocks = zone_blocks;
745 	sdkp->nr_zones = nr_zones;
746 	sdkp->rev_wp_offset = kvcalloc(nr_zones, sizeof(u32), GFP_KERNEL);
747 	if (!sdkp->rev_wp_offset) {
748 		ret = -ENOMEM;
749 		memalloc_noio_restore(flags);
750 		goto unlock;
751 	}
752 
753 	ret = blk_revalidate_disk_zones(disk, sd_zbc_revalidate_zones_cb);
754 
755 	memalloc_noio_restore(flags);
756 	kvfree(sdkp->rev_wp_offset);
757 	sdkp->rev_wp_offset = NULL;
758 
759 	if (ret) {
760 		sdkp->zone_blocks = 0;
761 		sdkp->nr_zones = 0;
762 		sdkp->capacity = 0;
763 		goto unlock;
764 	}
765 
766 	max_append = min_t(u32, logical_to_sectors(sdkp->device, zone_blocks),
767 			   q->limits.max_segments << (PAGE_SHIFT - 9));
768 	max_append = min_t(u32, max_append, queue_max_hw_sectors(q));
769 
770 	blk_queue_max_zone_append_sectors(q, max_append);
771 
772 	sd_zbc_print_zones(sdkp);
773 
774 unlock:
775 	mutex_unlock(&sdkp->rev_mutex);
776 
777 	return ret;
778 }
779 
780 int sd_zbc_read_zones(struct scsi_disk *sdkp, unsigned char *buf)
781 {
782 	struct gendisk *disk = sdkp->disk;
783 	struct request_queue *q = disk->queue;
784 	unsigned int nr_zones;
785 	u32 zone_blocks = 0;
786 	int ret;
787 
788 	if (!sd_is_zoned(sdkp))
789 		/*
790 		 * Device managed or normal SCSI disk,
791 		 * no special handling required
792 		 */
793 		return 0;
794 
795 	/* READ16/WRITE16 is mandatory for ZBC disks */
796 	sdkp->device->use_16_for_rw = 1;
797 	sdkp->device->use_10_for_rw = 0;
798 
799 	if (!blk_queue_is_zoned(q)) {
800 		/*
801 		 * This can happen for a host aware disk with partitions.
802 		 * The block device zone information was already cleared
803 		 * by blk_queue_set_zoned(). Only clear the scsi disk zone
804 		 * information and exit early.
805 		 */
806 		sd_zbc_clear_zone_info(sdkp);
807 		return 0;
808 	}
809 
810 	/* Check zoned block device characteristics (unconstrained reads) */
811 	ret = sd_zbc_check_zoned_characteristics(sdkp, buf);
812 	if (ret)
813 		goto err;
814 
815 	/* Check the device capacity reported by report zones */
816 	ret = sd_zbc_check_capacity(sdkp, buf, &zone_blocks);
817 	if (ret != 0)
818 		goto err;
819 
820 	/* The drive satisfies the kernel restrictions: set it up */
821 	blk_queue_flag_set(QUEUE_FLAG_ZONE_RESETALL, q);
822 	blk_queue_required_elevator_features(q, ELEVATOR_F_ZBD_SEQ_WRITE);
823 	if (sdkp->zones_max_open == U32_MAX)
824 		blk_queue_max_open_zones(q, 0);
825 	else
826 		blk_queue_max_open_zones(q, sdkp->zones_max_open);
827 	blk_queue_max_active_zones(q, 0);
828 	nr_zones = round_up(sdkp->capacity, zone_blocks) >> ilog2(zone_blocks);
829 
830 	/*
831 	 * Per ZBC and ZAC specifications, writes in sequential write required
832 	 * zones of host-managed devices must be aligned to the device physical
833 	 * block size.
834 	 */
835 	if (blk_queue_zoned_model(q) == BLK_ZONED_HM)
836 		blk_queue_zone_write_granularity(q, sdkp->physical_block_size);
837 
838 	sdkp->rev_nr_zones = nr_zones;
839 	sdkp->rev_zone_blocks = zone_blocks;
840 
841 	return 0;
842 
843 err:
844 	sdkp->capacity = 0;
845 
846 	return ret;
847 }
848