1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*******************************************************************************
3  * Filename:  target_core_pr.c
4  *
5  * This file contains SPC-3 compliant persistent reservations and
6  * legacy SPC-2 reservations with compatible reservation handling (CRH=1)
7  *
8  * (c) Copyright 2009-2013 Datera, Inc.
9  *
10  * Nicholas A. Bellinger <nab@kernel.org>
11  *
12  ******************************************************************************/
13 
14 #include <linux/slab.h>
15 #include <linux/spinlock.h>
16 #include <linux/list.h>
17 #include <linux/vmalloc.h>
18 #include <linux/file.h>
19 #include <linux/fcntl.h>
20 #include <linux/fs.h>
21 #include <scsi/scsi_proto.h>
22 #include <asm/unaligned.h>
23 
24 #include <target/target_core_base.h>
25 #include <target/target_core_backend.h>
26 #include <target/target_core_fabric.h>
27 
28 #include "target_core_internal.h"
29 #include "target_core_pr.h"
30 #include "target_core_ua.h"
31 
32 /*
33  * Used for Specify Initiator Ports Capable Bit (SPEC_I_PT)
34  */
35 struct pr_transport_id_holder {
36 	struct t10_pr_registration *dest_pr_reg;
37 	struct se_portal_group *dest_tpg;
38 	struct se_node_acl *dest_node_acl;
39 	struct se_dev_entry *dest_se_deve;
40 	struct list_head dest_list;
41 };
42 
43 void core_pr_dump_initiator_port(
44 	struct t10_pr_registration *pr_reg,
45 	char *buf,
46 	u32 size)
47 {
48 	if (!pr_reg->isid_present_at_reg) {
49 		buf[0] = '\0';
50 		return;
51 	}
52 
53 	snprintf(buf, size, ",i,0x%s", pr_reg->pr_reg_isid);
54 }
55 
56 enum register_type {
57 	REGISTER,
58 	REGISTER_AND_IGNORE_EXISTING_KEY,
59 	REGISTER_AND_MOVE,
60 };
61 
62 enum preempt_type {
63 	PREEMPT,
64 	PREEMPT_AND_ABORT,
65 };
66 
67 static void __core_scsi3_complete_pro_release(struct se_device *, struct se_node_acl *,
68 					      struct t10_pr_registration *, int, int);
69 
70 static int is_reservation_holder(
71 	struct t10_pr_registration *pr_res_holder,
72 	struct t10_pr_registration *pr_reg)
73 {
74 	int pr_res_type;
75 
76 	if (pr_res_holder) {
77 		pr_res_type = pr_res_holder->pr_res_type;
78 
79 		return pr_res_holder == pr_reg ||
80 		       pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG ||
81 		       pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG;
82 	}
83 	return 0;
84 }
85 
86 static sense_reason_t
87 target_scsi2_reservation_check(struct se_cmd *cmd)
88 {
89 	struct se_device *dev = cmd->se_dev;
90 	struct se_session *sess = cmd->se_sess;
91 
92 	switch (cmd->t_task_cdb[0]) {
93 	case INQUIRY:
94 	case RELEASE:
95 	case RELEASE_10:
96 		return 0;
97 	default:
98 		break;
99 	}
100 
101 	if (!dev->reservation_holder || !sess)
102 		return 0;
103 
104 	if (dev->reservation_holder->se_node_acl != sess->se_node_acl)
105 		return TCM_RESERVATION_CONFLICT;
106 
107 	if (dev->dev_reservation_flags & DRF_SPC2_RESERVATIONS_WITH_ISID) {
108 		if (dev->dev_res_bin_isid != sess->sess_bin_isid)
109 			return TCM_RESERVATION_CONFLICT;
110 	}
111 
112 	return 0;
113 }
114 
115 static struct t10_pr_registration *core_scsi3_locate_pr_reg(struct se_device *,
116 					struct se_node_acl *, struct se_session *);
117 static void core_scsi3_put_pr_reg(struct t10_pr_registration *);
118 
119 static int target_check_scsi2_reservation_conflict(struct se_cmd *cmd)
120 {
121 	struct se_session *se_sess = cmd->se_sess;
122 	struct se_device *dev = cmd->se_dev;
123 	struct t10_pr_registration *pr_reg;
124 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
125 	int conflict = 0;
126 
127 	pr_reg = core_scsi3_locate_pr_reg(cmd->se_dev, se_sess->se_node_acl,
128 			se_sess);
129 	if (pr_reg) {
130 		/*
131 		 * From spc4r17 5.7.3 Exceptions to SPC-2 RESERVE and RELEASE
132 		 * behavior
133 		 *
134 		 * A RESERVE(6) or RESERVE(10) command shall complete with GOOD
135 		 * status, but no reservation shall be established and the
136 		 * persistent reservation shall not be changed, if the command
137 		 * is received from a) and b) below.
138 		 *
139 		 * A RELEASE(6) or RELEASE(10) command shall complete with GOOD
140 		 * status, but the persistent reservation shall not be released,
141 		 * if the command is received from a) and b)
142 		 *
143 		 * a) An I_T nexus that is a persistent reservation holder; or
144 		 * b) An I_T nexus that is registered if a registrants only or
145 		 *    all registrants type persistent reservation is present.
146 		 *
147 		 * In all other cases, a RESERVE(6) command, RESERVE(10) command,
148 		 * RELEASE(6) command, or RELEASE(10) command shall be processed
149 		 * as defined in SPC-2.
150 		 */
151 		if (pr_reg->pr_res_holder) {
152 			core_scsi3_put_pr_reg(pr_reg);
153 			return 1;
154 		}
155 		if ((pr_reg->pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_REGONLY) ||
156 		    (pr_reg->pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_REGONLY) ||
157 		    (pr_reg->pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG) ||
158 		    (pr_reg->pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG)) {
159 			core_scsi3_put_pr_reg(pr_reg);
160 			return 1;
161 		}
162 		core_scsi3_put_pr_reg(pr_reg);
163 		conflict = 1;
164 	} else {
165 		/*
166 		 * Following spc2r20 5.5.1 Reservations overview:
167 		 *
168 		 * If a logical unit has executed a PERSISTENT RESERVE OUT
169 		 * command with the REGISTER or the REGISTER AND IGNORE
170 		 * EXISTING KEY service action and is still registered by any
171 		 * initiator, all RESERVE commands and all RELEASE commands
172 		 * regardless of initiator shall conflict and shall terminate
173 		 * with a RESERVATION CONFLICT status.
174 		 */
175 		spin_lock(&pr_tmpl->registration_lock);
176 		conflict = (list_empty(&pr_tmpl->registration_list)) ? 0 : 1;
177 		spin_unlock(&pr_tmpl->registration_lock);
178 	}
179 
180 	if (conflict) {
181 		pr_err("Received legacy SPC-2 RESERVE/RELEASE"
182 			" while active SPC-3 registrations exist,"
183 			" returning RESERVATION_CONFLICT\n");
184 		return -EBUSY;
185 	}
186 
187 	return 0;
188 }
189 
190 void target_release_reservation(struct se_device *dev)
191 {
192 	dev->reservation_holder = NULL;
193 	dev->dev_reservation_flags &= ~DRF_SPC2_RESERVATIONS;
194 	if (dev->dev_reservation_flags & DRF_SPC2_RESERVATIONS_WITH_ISID) {
195 		dev->dev_res_bin_isid = 0;
196 		dev->dev_reservation_flags &= ~DRF_SPC2_RESERVATIONS_WITH_ISID;
197 	}
198 }
199 
200 sense_reason_t
201 target_scsi2_reservation_release(struct se_cmd *cmd)
202 {
203 	struct se_device *dev = cmd->se_dev;
204 	struct se_session *sess = cmd->se_sess;
205 	struct se_portal_group *tpg;
206 	int rc;
207 
208 	if (!sess || !sess->se_tpg)
209 		goto out;
210 	rc = target_check_scsi2_reservation_conflict(cmd);
211 	if (rc == 1)
212 		goto out;
213 	if (rc < 0)
214 		return TCM_RESERVATION_CONFLICT;
215 
216 	spin_lock(&dev->dev_reservation_lock);
217 	if (!dev->reservation_holder || !sess)
218 		goto out_unlock;
219 
220 	if (dev->reservation_holder->se_node_acl != sess->se_node_acl)
221 		goto out_unlock;
222 
223 	if (dev->dev_res_bin_isid != sess->sess_bin_isid)
224 		goto out_unlock;
225 
226 	target_release_reservation(dev);
227 	tpg = sess->se_tpg;
228 	pr_debug("SCSI-2 Released reservation for %s LUN: %llu ->"
229 		" MAPPED LUN: %llu for %s\n",
230 		tpg->se_tpg_tfo->fabric_name,
231 		cmd->se_lun->unpacked_lun, cmd->orig_fe_lun,
232 		sess->se_node_acl->initiatorname);
233 
234 out_unlock:
235 	spin_unlock(&dev->dev_reservation_lock);
236 out:
237 	target_complete_cmd(cmd, GOOD);
238 	return 0;
239 }
240 
241 sense_reason_t
242 target_scsi2_reservation_reserve(struct se_cmd *cmd)
243 {
244 	struct se_device *dev = cmd->se_dev;
245 	struct se_session *sess = cmd->se_sess;
246 	struct se_portal_group *tpg;
247 	sense_reason_t ret = 0;
248 	int rc;
249 
250 	if ((cmd->t_task_cdb[1] & 0x01) &&
251 	    (cmd->t_task_cdb[1] & 0x02)) {
252 		pr_err("LongIO and Obsolete Bits set, returning ILLEGAL_REQUEST\n");
253 		return TCM_UNSUPPORTED_SCSI_OPCODE;
254 	}
255 	/*
256 	 * This is currently the case for target_core_mod passthrough struct se_cmd
257 	 * ops
258 	 */
259 	if (!sess || !sess->se_tpg)
260 		goto out;
261 	rc = target_check_scsi2_reservation_conflict(cmd);
262 	if (rc == 1)
263 		goto out;
264 
265 	if (rc < 0)
266 		return TCM_RESERVATION_CONFLICT;
267 
268 	tpg = sess->se_tpg;
269 	spin_lock(&dev->dev_reservation_lock);
270 	if (dev->reservation_holder &&
271 	    dev->reservation_holder->se_node_acl != sess->se_node_acl) {
272 		pr_err("SCSI-2 RESERVATION CONFLIFT for %s fabric\n",
273 			tpg->se_tpg_tfo->fabric_name);
274 		pr_err("Original reserver LUN: %llu %s\n",
275 			cmd->se_lun->unpacked_lun,
276 			dev->reservation_holder->se_node_acl->initiatorname);
277 		pr_err("Current attempt - LUN: %llu -> MAPPED LUN: %llu"
278 			" from %s \n", cmd->se_lun->unpacked_lun,
279 			cmd->orig_fe_lun,
280 			sess->se_node_acl->initiatorname);
281 		ret = TCM_RESERVATION_CONFLICT;
282 		goto out_unlock;
283 	}
284 
285 	dev->reservation_holder = sess;
286 	dev->dev_reservation_flags |= DRF_SPC2_RESERVATIONS;
287 	if (sess->sess_bin_isid != 0) {
288 		dev->dev_res_bin_isid = sess->sess_bin_isid;
289 		dev->dev_reservation_flags |= DRF_SPC2_RESERVATIONS_WITH_ISID;
290 	}
291 	pr_debug("SCSI-2 Reserved %s LUN: %llu -> MAPPED LUN: %llu"
292 		" for %s\n", tpg->se_tpg_tfo->fabric_name,
293 		cmd->se_lun->unpacked_lun, cmd->orig_fe_lun,
294 		sess->se_node_acl->initiatorname);
295 
296 out_unlock:
297 	spin_unlock(&dev->dev_reservation_lock);
298 out:
299 	if (!ret)
300 		target_complete_cmd(cmd, GOOD);
301 	return ret;
302 }
303 
304 
305 /*
306  * Begin SPC-3/SPC-4 Persistent Reservations emulation support
307  *
308  * This function is called by those initiator ports who are *NOT*
309  * the active PR reservation holder when a reservation is present.
310  */
311 static int core_scsi3_pr_seq_non_holder(struct se_cmd *cmd, u32 pr_reg_type,
312 					bool isid_mismatch)
313 {
314 	unsigned char *cdb = cmd->t_task_cdb;
315 	struct se_session *se_sess = cmd->se_sess;
316 	struct se_node_acl *nacl = se_sess->se_node_acl;
317 	int other_cdb = 0;
318 	int registered_nexus = 0, ret = 1; /* Conflict by default */
319 	int all_reg = 0, reg_only = 0; /* ALL_REG, REG_ONLY */
320 	int we = 0; /* Write Exclusive */
321 	int legacy = 0; /* Act like a legacy device and return
322 			 * RESERVATION CONFLICT on some CDBs */
323 
324 	if (isid_mismatch) {
325 		registered_nexus = 0;
326 	} else {
327 		struct se_dev_entry *se_deve;
328 
329 		rcu_read_lock();
330 		se_deve = target_nacl_find_deve(nacl, cmd->orig_fe_lun);
331 		if (se_deve)
332 			registered_nexus = test_bit(DEF_PR_REG_ACTIVE,
333 						    &se_deve->deve_flags);
334 		rcu_read_unlock();
335 	}
336 
337 	switch (pr_reg_type) {
338 	case PR_TYPE_WRITE_EXCLUSIVE:
339 		we = 1;
340 	case PR_TYPE_EXCLUSIVE_ACCESS:
341 		/*
342 		 * Some commands are only allowed for the persistent reservation
343 		 * holder.
344 		 */
345 		break;
346 	case PR_TYPE_WRITE_EXCLUSIVE_REGONLY:
347 		we = 1;
348 		/* fall through */
349 	case PR_TYPE_EXCLUSIVE_ACCESS_REGONLY:
350 		/*
351 		 * Some commands are only allowed for registered I_T Nexuses.
352 		 */
353 		reg_only = 1;
354 		break;
355 	case PR_TYPE_WRITE_EXCLUSIVE_ALLREG:
356 		we = 1;
357 		/* fall through */
358 	case PR_TYPE_EXCLUSIVE_ACCESS_ALLREG:
359 		/*
360 		 * Each registered I_T Nexus is a reservation holder.
361 		 */
362 		all_reg = 1;
363 		break;
364 	default:
365 		return -EINVAL;
366 	}
367 	/*
368 	 * Referenced from spc4r17 table 45 for *NON* PR holder access
369 	 */
370 	switch (cdb[0]) {
371 	case SECURITY_PROTOCOL_IN:
372 		if (registered_nexus)
373 			return 0;
374 		ret = (we) ? 0 : 1;
375 		break;
376 	case MODE_SENSE:
377 	case MODE_SENSE_10:
378 	case READ_ATTRIBUTE:
379 	case READ_BUFFER:
380 	case RECEIVE_DIAGNOSTIC:
381 		if (legacy) {
382 			ret = 1;
383 			break;
384 		}
385 		if (registered_nexus) {
386 			ret = 0;
387 			break;
388 		}
389 		ret = (we) ? 0 : 1; /* Allowed Write Exclusive */
390 		break;
391 	case PERSISTENT_RESERVE_OUT:
392 		/*
393 		 * This follows PERSISTENT_RESERVE_OUT service actions that
394 		 * are allowed in the presence of various reservations.
395 		 * See spc4r17, table 46
396 		 */
397 		switch (cdb[1] & 0x1f) {
398 		case PRO_CLEAR:
399 		case PRO_PREEMPT:
400 		case PRO_PREEMPT_AND_ABORT:
401 			ret = (registered_nexus) ? 0 : 1;
402 			break;
403 		case PRO_REGISTER:
404 		case PRO_REGISTER_AND_IGNORE_EXISTING_KEY:
405 			ret = 0;
406 			break;
407 		case PRO_REGISTER_AND_MOVE:
408 		case PRO_RESERVE:
409 			ret = 1;
410 			break;
411 		case PRO_RELEASE:
412 			ret = (registered_nexus) ? 0 : 1;
413 			break;
414 		default:
415 			pr_err("Unknown PERSISTENT_RESERVE_OUT service"
416 				" action: 0x%02x\n", cdb[1] & 0x1f);
417 			return -EINVAL;
418 		}
419 		break;
420 	case RELEASE:
421 	case RELEASE_10:
422 		/* Handled by CRH=1 in target_scsi2_reservation_release() */
423 		ret = 0;
424 		break;
425 	case RESERVE:
426 	case RESERVE_10:
427 		/* Handled by CRH=1 in target_scsi2_reservation_reserve() */
428 		ret = 0;
429 		break;
430 	case TEST_UNIT_READY:
431 		ret = (legacy) ? 1 : 0; /* Conflict for legacy */
432 		break;
433 	case MAINTENANCE_IN:
434 		switch (cdb[1] & 0x1f) {
435 		case MI_MANAGEMENT_PROTOCOL_IN:
436 			if (registered_nexus) {
437 				ret = 0;
438 				break;
439 			}
440 			ret = (we) ? 0 : 1; /* Allowed Write Exclusive */
441 			break;
442 		case MI_REPORT_SUPPORTED_OPERATION_CODES:
443 		case MI_REPORT_SUPPORTED_TASK_MANAGEMENT_FUNCTIONS:
444 			if (legacy) {
445 				ret = 1;
446 				break;
447 			}
448 			if (registered_nexus) {
449 				ret = 0;
450 				break;
451 			}
452 			ret = (we) ? 0 : 1; /* Allowed Write Exclusive */
453 			break;
454 		case MI_REPORT_ALIASES:
455 		case MI_REPORT_IDENTIFYING_INFORMATION:
456 		case MI_REPORT_PRIORITY:
457 		case MI_REPORT_TARGET_PGS:
458 		case MI_REPORT_TIMESTAMP:
459 			ret = 0; /* Allowed */
460 			break;
461 		default:
462 			pr_err("Unknown MI Service Action: 0x%02x\n",
463 				(cdb[1] & 0x1f));
464 			return -EINVAL;
465 		}
466 		break;
467 	case ACCESS_CONTROL_IN:
468 	case ACCESS_CONTROL_OUT:
469 	case INQUIRY:
470 	case LOG_SENSE:
471 	case SERVICE_ACTION_IN_12:
472 	case REPORT_LUNS:
473 	case REQUEST_SENSE:
474 	case PERSISTENT_RESERVE_IN:
475 		ret = 0; /*/ Allowed CDBs */
476 		break;
477 	default:
478 		other_cdb = 1;
479 		break;
480 	}
481 	/*
482 	 * Case where the CDB is explicitly allowed in the above switch
483 	 * statement.
484 	 */
485 	if (!ret && !other_cdb) {
486 		pr_debug("Allowing explicit CDB: 0x%02x for %s"
487 			" reservation holder\n", cdb[0],
488 			core_scsi3_pr_dump_type(pr_reg_type));
489 
490 		return ret;
491 	}
492 	/*
493 	 * Check if write exclusive initiator ports *NOT* holding the
494 	 * WRITE_EXCLUSIVE_* reservation.
495 	 */
496 	if (we && !registered_nexus) {
497 		if (cmd->data_direction == DMA_TO_DEVICE) {
498 			/*
499 			 * Conflict for write exclusive
500 			 */
501 			pr_debug("%s Conflict for unregistered nexus"
502 				" %s CDB: 0x%02x to %s reservation\n",
503 				transport_dump_cmd_direction(cmd),
504 				se_sess->se_node_acl->initiatorname, cdb[0],
505 				core_scsi3_pr_dump_type(pr_reg_type));
506 			return 1;
507 		} else {
508 			/*
509 			 * Allow non WRITE CDBs for all Write Exclusive
510 			 * PR TYPEs to pass for registered and
511 			 * non-registered_nexuxes NOT holding the reservation.
512 			 *
513 			 * We only make noise for the unregisterd nexuses,
514 			 * as we expect registered non-reservation holding
515 			 * nexuses to issue CDBs.
516 			 */
517 
518 			if (!registered_nexus) {
519 				pr_debug("Allowing implicit CDB: 0x%02x"
520 					" for %s reservation on unregistered"
521 					" nexus\n", cdb[0],
522 					core_scsi3_pr_dump_type(pr_reg_type));
523 			}
524 
525 			return 0;
526 		}
527 	} else if ((reg_only) || (all_reg)) {
528 		if (registered_nexus) {
529 			/*
530 			 * For PR_*_REG_ONLY and PR_*_ALL_REG reservations,
531 			 * allow commands from registered nexuses.
532 			 */
533 
534 			pr_debug("Allowing implicit CDB: 0x%02x for %s"
535 				" reservation\n", cdb[0],
536 				core_scsi3_pr_dump_type(pr_reg_type));
537 
538 			return 0;
539 		}
540        } else if (we && registered_nexus) {
541                /*
542                 * Reads are allowed for Write Exclusive locks
543                 * from all registrants.
544                 */
545                if (cmd->data_direction == DMA_FROM_DEVICE) {
546                        pr_debug("Allowing READ CDB: 0x%02x for %s"
547                                " reservation\n", cdb[0],
548                                core_scsi3_pr_dump_type(pr_reg_type));
549 
550                        return 0;
551                }
552 	}
553 	pr_debug("%s Conflict for %sregistered nexus %s CDB: 0x%2x"
554 		" for %s reservation\n", transport_dump_cmd_direction(cmd),
555 		(registered_nexus) ? "" : "un",
556 		se_sess->se_node_acl->initiatorname, cdb[0],
557 		core_scsi3_pr_dump_type(pr_reg_type));
558 
559 	return 1; /* Conflict by default */
560 }
561 
562 static sense_reason_t
563 target_scsi3_pr_reservation_check(struct se_cmd *cmd)
564 {
565 	struct se_device *dev = cmd->se_dev;
566 	struct se_session *sess = cmd->se_sess;
567 	u32 pr_reg_type;
568 	bool isid_mismatch = false;
569 
570 	if (!dev->dev_pr_res_holder)
571 		return 0;
572 
573 	pr_reg_type = dev->dev_pr_res_holder->pr_res_type;
574 	cmd->pr_res_key = dev->dev_pr_res_holder->pr_res_key;
575 	if (dev->dev_pr_res_holder->pr_reg_nacl != sess->se_node_acl)
576 		goto check_nonholder;
577 
578 	if (dev->dev_pr_res_holder->isid_present_at_reg) {
579 		if (dev->dev_pr_res_holder->pr_reg_bin_isid !=
580 		    sess->sess_bin_isid) {
581 			isid_mismatch = true;
582 			goto check_nonholder;
583 		}
584 	}
585 
586 	return 0;
587 
588 check_nonholder:
589 	if (core_scsi3_pr_seq_non_holder(cmd, pr_reg_type, isid_mismatch))
590 		return TCM_RESERVATION_CONFLICT;
591 	return 0;
592 }
593 
594 static u32 core_scsi3_pr_generation(struct se_device *dev)
595 {
596 	u32 prg;
597 
598 	/*
599 	 * PRGeneration field shall contain the value of a 32-bit wrapping
600 	 * counter mainted by the device server.
601 	 *
602 	 * Note that this is done regardless of Active Persist across
603 	 * Target PowerLoss (APTPL)
604 	 *
605 	 * See spc4r17 section 6.3.12 READ_KEYS service action
606 	 */
607 	spin_lock(&dev->dev_reservation_lock);
608 	prg = dev->t10_pr.pr_generation++;
609 	spin_unlock(&dev->dev_reservation_lock);
610 
611 	return prg;
612 }
613 
614 static struct t10_pr_registration *__core_scsi3_do_alloc_registration(
615 	struct se_device *dev,
616 	struct se_node_acl *nacl,
617 	struct se_lun *lun,
618 	struct se_dev_entry *dest_deve,
619 	u64 mapped_lun,
620 	unsigned char *isid,
621 	u64 sa_res_key,
622 	int all_tg_pt,
623 	int aptpl)
624 {
625 	struct t10_pr_registration *pr_reg;
626 
627 	pr_reg = kmem_cache_zalloc(t10_pr_reg_cache, GFP_ATOMIC);
628 	if (!pr_reg) {
629 		pr_err("Unable to allocate struct t10_pr_registration\n");
630 		return NULL;
631 	}
632 
633 	INIT_LIST_HEAD(&pr_reg->pr_reg_list);
634 	INIT_LIST_HEAD(&pr_reg->pr_reg_abort_list);
635 	INIT_LIST_HEAD(&pr_reg->pr_reg_aptpl_list);
636 	INIT_LIST_HEAD(&pr_reg->pr_reg_atp_list);
637 	INIT_LIST_HEAD(&pr_reg->pr_reg_atp_mem_list);
638 	atomic_set(&pr_reg->pr_res_holders, 0);
639 	pr_reg->pr_reg_nacl = nacl;
640 	/*
641 	 * For destination registrations for ALL_TG_PT=1 and SPEC_I_PT=1,
642 	 * the se_dev_entry->pr_ref will have been already obtained by
643 	 * core_get_se_deve_from_rtpi() or __core_scsi3_alloc_registration().
644 	 *
645 	 * Otherwise, locate se_dev_entry now and obtain a reference until
646 	 * registration completes in __core_scsi3_add_registration().
647 	 */
648 	if (dest_deve) {
649 		pr_reg->pr_reg_deve = dest_deve;
650 	} else {
651 		rcu_read_lock();
652 		pr_reg->pr_reg_deve = target_nacl_find_deve(nacl, mapped_lun);
653 		if (!pr_reg->pr_reg_deve) {
654 			rcu_read_unlock();
655 			pr_err("Unable to locate PR deve %s mapped_lun: %llu\n",
656 				nacl->initiatorname, mapped_lun);
657 			kmem_cache_free(t10_pr_reg_cache, pr_reg);
658 			return NULL;
659 		}
660 		kref_get(&pr_reg->pr_reg_deve->pr_kref);
661 		rcu_read_unlock();
662 	}
663 	pr_reg->pr_res_mapped_lun = mapped_lun;
664 	pr_reg->pr_aptpl_target_lun = lun->unpacked_lun;
665 	pr_reg->tg_pt_sep_rtpi = lun->lun_rtpi;
666 	pr_reg->pr_res_key = sa_res_key;
667 	pr_reg->pr_reg_all_tg_pt = all_tg_pt;
668 	pr_reg->pr_reg_aptpl = aptpl;
669 	/*
670 	 * If an ISID value for this SCSI Initiator Port exists,
671 	 * save it to the registration now.
672 	 */
673 	if (isid != NULL) {
674 		pr_reg->pr_reg_bin_isid = get_unaligned_be64(isid);
675 		snprintf(pr_reg->pr_reg_isid, PR_REG_ISID_LEN, "%s", isid);
676 		pr_reg->isid_present_at_reg = 1;
677 	}
678 
679 	return pr_reg;
680 }
681 
682 static int core_scsi3_lunacl_depend_item(struct se_dev_entry *);
683 static void core_scsi3_lunacl_undepend_item(struct se_dev_entry *);
684 
685 /*
686  * Function used for handling PR registrations for ALL_TG_PT=1 and ALL_TG_PT=0
687  * modes.
688  */
689 static struct t10_pr_registration *__core_scsi3_alloc_registration(
690 	struct se_device *dev,
691 	struct se_node_acl *nacl,
692 	struct se_lun *lun,
693 	struct se_dev_entry *deve,
694 	u64 mapped_lun,
695 	unsigned char *isid,
696 	u64 sa_res_key,
697 	int all_tg_pt,
698 	int aptpl)
699 {
700 	struct se_dev_entry *deve_tmp;
701 	struct se_node_acl *nacl_tmp;
702 	struct se_lun_acl *lacl_tmp;
703 	struct se_lun *lun_tmp, *next, *dest_lun;
704 	const struct target_core_fabric_ops *tfo = nacl->se_tpg->se_tpg_tfo;
705 	struct t10_pr_registration *pr_reg, *pr_reg_atp, *pr_reg_tmp, *pr_reg_tmp_safe;
706 	int ret;
707 	/*
708 	 * Create a registration for the I_T Nexus upon which the
709 	 * PROUT REGISTER was received.
710 	 */
711 	pr_reg = __core_scsi3_do_alloc_registration(dev, nacl, lun, deve, mapped_lun,
712 						    isid, sa_res_key, all_tg_pt,
713 						    aptpl);
714 	if (!pr_reg)
715 		return NULL;
716 	/*
717 	 * Return pointer to pr_reg for ALL_TG_PT=0
718 	 */
719 	if (!all_tg_pt)
720 		return pr_reg;
721 	/*
722 	 * Create list of matching SCSI Initiator Port registrations
723 	 * for ALL_TG_PT=1
724 	 */
725 	spin_lock(&dev->se_port_lock);
726 	list_for_each_entry_safe(lun_tmp, next, &dev->dev_sep_list, lun_dev_link) {
727 		if (!percpu_ref_tryget_live(&lun_tmp->lun_ref))
728 			continue;
729 		spin_unlock(&dev->se_port_lock);
730 
731 		spin_lock(&lun_tmp->lun_deve_lock);
732 		list_for_each_entry(deve_tmp, &lun_tmp->lun_deve_list, lun_link) {
733 			/*
734 			 * This pointer will be NULL for demo mode MappedLUNs
735 			 * that have not been make explicit via a ConfigFS
736 			 * MappedLUN group for the SCSI Initiator Node ACL.
737 			 */
738 			if (!deve_tmp->se_lun_acl)
739 				continue;
740 
741 			lacl_tmp = rcu_dereference_check(deve_tmp->se_lun_acl,
742 						lockdep_is_held(&lun_tmp->lun_deve_lock));
743 			nacl_tmp = lacl_tmp->se_lun_nacl;
744 			/*
745 			 * Skip the matching struct se_node_acl that is allocated
746 			 * above..
747 			 */
748 			if (nacl == nacl_tmp)
749 				continue;
750 			/*
751 			 * Only perform PR registrations for target ports on
752 			 * the same fabric module as the REGISTER w/ ALL_TG_PT=1
753 			 * arrived.
754 			 */
755 			if (tfo != nacl_tmp->se_tpg->se_tpg_tfo)
756 				continue;
757 			/*
758 			 * Look for a matching Initiator Node ACL in ASCII format
759 			 */
760 			if (strcmp(nacl->initiatorname, nacl_tmp->initiatorname))
761 				continue;
762 
763 			kref_get(&deve_tmp->pr_kref);
764 			spin_unlock(&lun_tmp->lun_deve_lock);
765 			/*
766 			 * Grab a configfs group dependency that is released
767 			 * for the exception path at label out: below, or upon
768 			 * completion of adding ALL_TG_PT=1 registrations in
769 			 * __core_scsi3_add_registration()
770 			 */
771 			ret = core_scsi3_lunacl_depend_item(deve_tmp);
772 			if (ret < 0) {
773 				pr_err("core_scsi3_lunacl_depend"
774 						"_item() failed\n");
775 				percpu_ref_put(&lun_tmp->lun_ref);
776 				kref_put(&deve_tmp->pr_kref, target_pr_kref_release);
777 				goto out;
778 			}
779 			/*
780 			 * Located a matching SCSI Initiator Port on a different
781 			 * port, allocate the pr_reg_atp and attach it to the
782 			 * pr_reg->pr_reg_atp_list that will be processed once
783 			 * the original *pr_reg is processed in
784 			 * __core_scsi3_add_registration()
785 			 */
786 			dest_lun = rcu_dereference_check(deve_tmp->se_lun,
787 				kref_read(&deve_tmp->pr_kref) != 0);
788 
789 			pr_reg_atp = __core_scsi3_do_alloc_registration(dev,
790 						nacl_tmp, dest_lun, deve_tmp,
791 						deve_tmp->mapped_lun, NULL,
792 						sa_res_key, all_tg_pt, aptpl);
793 			if (!pr_reg_atp) {
794 				percpu_ref_put(&lun_tmp->lun_ref);
795 				core_scsi3_lunacl_undepend_item(deve_tmp);
796 				goto out;
797 			}
798 
799 			list_add_tail(&pr_reg_atp->pr_reg_atp_mem_list,
800 				      &pr_reg->pr_reg_atp_list);
801 			spin_lock(&lun_tmp->lun_deve_lock);
802 		}
803 		spin_unlock(&lun_tmp->lun_deve_lock);
804 
805 		spin_lock(&dev->se_port_lock);
806 		percpu_ref_put(&lun_tmp->lun_ref);
807 	}
808 	spin_unlock(&dev->se_port_lock);
809 
810 	return pr_reg;
811 out:
812 	list_for_each_entry_safe(pr_reg_tmp, pr_reg_tmp_safe,
813 			&pr_reg->pr_reg_atp_list, pr_reg_atp_mem_list) {
814 		list_del(&pr_reg_tmp->pr_reg_atp_mem_list);
815 		core_scsi3_lunacl_undepend_item(pr_reg_tmp->pr_reg_deve);
816 		kmem_cache_free(t10_pr_reg_cache, pr_reg_tmp);
817 	}
818 	kmem_cache_free(t10_pr_reg_cache, pr_reg);
819 	return NULL;
820 }
821 
822 int core_scsi3_alloc_aptpl_registration(
823 	struct t10_reservation *pr_tmpl,
824 	u64 sa_res_key,
825 	unsigned char *i_port,
826 	unsigned char *isid,
827 	u64 mapped_lun,
828 	unsigned char *t_port,
829 	u16 tpgt,
830 	u64 target_lun,
831 	int res_holder,
832 	int all_tg_pt,
833 	u8 type)
834 {
835 	struct t10_pr_registration *pr_reg;
836 
837 	if (!i_port || !t_port || !sa_res_key) {
838 		pr_err("Illegal parameters for APTPL registration\n");
839 		return -EINVAL;
840 	}
841 
842 	pr_reg = kmem_cache_zalloc(t10_pr_reg_cache, GFP_KERNEL);
843 	if (!pr_reg) {
844 		pr_err("Unable to allocate struct t10_pr_registration\n");
845 		return -ENOMEM;
846 	}
847 
848 	INIT_LIST_HEAD(&pr_reg->pr_reg_list);
849 	INIT_LIST_HEAD(&pr_reg->pr_reg_abort_list);
850 	INIT_LIST_HEAD(&pr_reg->pr_reg_aptpl_list);
851 	INIT_LIST_HEAD(&pr_reg->pr_reg_atp_list);
852 	INIT_LIST_HEAD(&pr_reg->pr_reg_atp_mem_list);
853 	atomic_set(&pr_reg->pr_res_holders, 0);
854 	pr_reg->pr_reg_nacl = NULL;
855 	pr_reg->pr_reg_deve = NULL;
856 	pr_reg->pr_res_mapped_lun = mapped_lun;
857 	pr_reg->pr_aptpl_target_lun = target_lun;
858 	pr_reg->pr_res_key = sa_res_key;
859 	pr_reg->pr_reg_all_tg_pt = all_tg_pt;
860 	pr_reg->pr_reg_aptpl = 1;
861 	pr_reg->pr_res_scope = 0; /* Always LUN_SCOPE */
862 	pr_reg->pr_res_type = type;
863 	/*
864 	 * If an ISID value had been saved in APTPL metadata for this
865 	 * SCSI Initiator Port, restore it now.
866 	 */
867 	if (isid != NULL) {
868 		pr_reg->pr_reg_bin_isid = get_unaligned_be64(isid);
869 		snprintf(pr_reg->pr_reg_isid, PR_REG_ISID_LEN, "%s", isid);
870 		pr_reg->isid_present_at_reg = 1;
871 	}
872 	/*
873 	 * Copy the i_port and t_port information from caller.
874 	 */
875 	snprintf(pr_reg->pr_iport, PR_APTPL_MAX_IPORT_LEN, "%s", i_port);
876 	snprintf(pr_reg->pr_tport, PR_APTPL_MAX_TPORT_LEN, "%s", t_port);
877 	pr_reg->pr_reg_tpgt = tpgt;
878 	/*
879 	 * Set pr_res_holder from caller, the pr_reg who is the reservation
880 	 * holder will get it's pointer set in core_scsi3_aptpl_reserve() once
881 	 * the Initiator Node LUN ACL from the fabric module is created for
882 	 * this registration.
883 	 */
884 	pr_reg->pr_res_holder = res_holder;
885 
886 	list_add_tail(&pr_reg->pr_reg_aptpl_list, &pr_tmpl->aptpl_reg_list);
887 	pr_debug("SPC-3 PR APTPL Successfully added registration%s from"
888 			" metadata\n", (res_holder) ? "+reservation" : "");
889 	return 0;
890 }
891 
892 static void core_scsi3_aptpl_reserve(
893 	struct se_device *dev,
894 	struct se_portal_group *tpg,
895 	struct se_node_acl *node_acl,
896 	struct t10_pr_registration *pr_reg)
897 {
898 	char i_buf[PR_REG_ISID_ID_LEN];
899 
900 	memset(i_buf, 0, PR_REG_ISID_ID_LEN);
901 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
902 
903 	spin_lock(&dev->dev_reservation_lock);
904 	dev->dev_pr_res_holder = pr_reg;
905 	spin_unlock(&dev->dev_reservation_lock);
906 
907 	pr_debug("SPC-3 PR [%s] Service Action: APTPL RESERVE created"
908 		" new reservation holder TYPE: %s ALL_TG_PT: %d\n",
909 		tpg->se_tpg_tfo->fabric_name,
910 		core_scsi3_pr_dump_type(pr_reg->pr_res_type),
911 		(pr_reg->pr_reg_all_tg_pt) ? 1 : 0);
912 	pr_debug("SPC-3 PR [%s] RESERVE Node: %s%s\n",
913 		tpg->se_tpg_tfo->fabric_name, node_acl->initiatorname,
914 		i_buf);
915 }
916 
917 static void __core_scsi3_add_registration(struct se_device *, struct se_node_acl *,
918 				struct t10_pr_registration *, enum register_type, int);
919 
920 static int __core_scsi3_check_aptpl_registration(
921 	struct se_device *dev,
922 	struct se_portal_group *tpg,
923 	struct se_lun *lun,
924 	u64 target_lun,
925 	struct se_node_acl *nacl,
926 	u64 mapped_lun)
927 {
928 	struct t10_pr_registration *pr_reg, *pr_reg_tmp;
929 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
930 	unsigned char i_port[PR_APTPL_MAX_IPORT_LEN];
931 	unsigned char t_port[PR_APTPL_MAX_TPORT_LEN];
932 	u16 tpgt;
933 
934 	memset(i_port, 0, PR_APTPL_MAX_IPORT_LEN);
935 	memset(t_port, 0, PR_APTPL_MAX_TPORT_LEN);
936 	/*
937 	 * Copy Initiator Port information from struct se_node_acl
938 	 */
939 	snprintf(i_port, PR_APTPL_MAX_IPORT_LEN, "%s", nacl->initiatorname);
940 	snprintf(t_port, PR_APTPL_MAX_TPORT_LEN, "%s",
941 			tpg->se_tpg_tfo->tpg_get_wwn(tpg));
942 	tpgt = tpg->se_tpg_tfo->tpg_get_tag(tpg);
943 	/*
944 	 * Look for the matching registrations+reservation from those
945 	 * created from APTPL metadata.  Note that multiple registrations
946 	 * may exist for fabrics that use ISIDs in their SCSI Initiator Port
947 	 * TransportIDs.
948 	 */
949 	spin_lock(&pr_tmpl->aptpl_reg_lock);
950 	list_for_each_entry_safe(pr_reg, pr_reg_tmp, &pr_tmpl->aptpl_reg_list,
951 				pr_reg_aptpl_list) {
952 
953 		if (!strcmp(pr_reg->pr_iport, i_port) &&
954 		     (pr_reg->pr_res_mapped_lun == mapped_lun) &&
955 		    !(strcmp(pr_reg->pr_tport, t_port)) &&
956 		     (pr_reg->pr_reg_tpgt == tpgt) &&
957 		     (pr_reg->pr_aptpl_target_lun == target_lun)) {
958 			/*
959 			 * Obtain the ->pr_reg_deve pointer + reference, that
960 			 * is released by __core_scsi3_add_registration() below.
961 			 */
962 			rcu_read_lock();
963 			pr_reg->pr_reg_deve = target_nacl_find_deve(nacl, mapped_lun);
964 			if (!pr_reg->pr_reg_deve) {
965 				pr_err("Unable to locate PR APTPL %s mapped_lun:"
966 					" %llu\n", nacl->initiatorname, mapped_lun);
967 				rcu_read_unlock();
968 				continue;
969 			}
970 			kref_get(&pr_reg->pr_reg_deve->pr_kref);
971 			rcu_read_unlock();
972 
973 			pr_reg->pr_reg_nacl = nacl;
974 			pr_reg->tg_pt_sep_rtpi = lun->lun_rtpi;
975 			list_del(&pr_reg->pr_reg_aptpl_list);
976 			spin_unlock(&pr_tmpl->aptpl_reg_lock);
977 			/*
978 			 * At this point all of the pointers in *pr_reg will
979 			 * be setup, so go ahead and add the registration.
980 			 */
981 			__core_scsi3_add_registration(dev, nacl, pr_reg, 0, 0);
982 			/*
983 			 * If this registration is the reservation holder,
984 			 * make that happen now..
985 			 */
986 			if (pr_reg->pr_res_holder)
987 				core_scsi3_aptpl_reserve(dev, tpg,
988 						nacl, pr_reg);
989 			/*
990 			 * Reenable pr_aptpl_active to accept new metadata
991 			 * updates once the SCSI device is active again..
992 			 */
993 			spin_lock(&pr_tmpl->aptpl_reg_lock);
994 			pr_tmpl->pr_aptpl_active = 1;
995 		}
996 	}
997 	spin_unlock(&pr_tmpl->aptpl_reg_lock);
998 
999 	return 0;
1000 }
1001 
1002 int core_scsi3_check_aptpl_registration(
1003 	struct se_device *dev,
1004 	struct se_portal_group *tpg,
1005 	struct se_lun *lun,
1006 	struct se_node_acl *nacl,
1007 	u64 mapped_lun)
1008 {
1009 	if (dev->dev_reservation_flags & DRF_SPC2_RESERVATIONS)
1010 		return 0;
1011 
1012 	return __core_scsi3_check_aptpl_registration(dev, tpg, lun,
1013 						     lun->unpacked_lun, nacl,
1014 						     mapped_lun);
1015 }
1016 
1017 static void __core_scsi3_dump_registration(
1018 	const struct target_core_fabric_ops *tfo,
1019 	struct se_device *dev,
1020 	struct se_node_acl *nacl,
1021 	struct t10_pr_registration *pr_reg,
1022 	enum register_type register_type)
1023 {
1024 	struct se_portal_group *se_tpg = nacl->se_tpg;
1025 	char i_buf[PR_REG_ISID_ID_LEN];
1026 
1027 	memset(&i_buf[0], 0, PR_REG_ISID_ID_LEN);
1028 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
1029 
1030 	pr_debug("SPC-3 PR [%s] Service Action: REGISTER%s Initiator"
1031 		" Node: %s%s\n", tfo->fabric_name, (register_type == REGISTER_AND_MOVE) ?
1032 		"_AND_MOVE" : (register_type == REGISTER_AND_IGNORE_EXISTING_KEY) ?
1033 		"_AND_IGNORE_EXISTING_KEY" : "", nacl->initiatorname,
1034 		i_buf);
1035 	pr_debug("SPC-3 PR [%s] registration on Target Port: %s,0x%04x\n",
1036 		 tfo->fabric_name, tfo->tpg_get_wwn(se_tpg),
1037 		tfo->tpg_get_tag(se_tpg));
1038 	pr_debug("SPC-3 PR [%s] for %s TCM Subsystem %s Object Target"
1039 		" Port(s)\n",  tfo->fabric_name,
1040 		(pr_reg->pr_reg_all_tg_pt) ? "ALL" : "SINGLE",
1041 		dev->transport->name);
1042 	pr_debug("SPC-3 PR [%s] SA Res Key: 0x%016Lx PRgeneration:"
1043 		" 0x%08x  APTPL: %d\n", tfo->fabric_name,
1044 		pr_reg->pr_res_key, pr_reg->pr_res_generation,
1045 		pr_reg->pr_reg_aptpl);
1046 }
1047 
1048 static void __core_scsi3_add_registration(
1049 	struct se_device *dev,
1050 	struct se_node_acl *nacl,
1051 	struct t10_pr_registration *pr_reg,
1052 	enum register_type register_type,
1053 	int register_move)
1054 {
1055 	const struct target_core_fabric_ops *tfo = nacl->se_tpg->se_tpg_tfo;
1056 	struct t10_pr_registration *pr_reg_tmp, *pr_reg_tmp_safe;
1057 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
1058 	struct se_dev_entry *deve;
1059 
1060 	/*
1061 	 * Increment PRgeneration counter for struct se_device upon a successful
1062 	 * REGISTER, see spc4r17 section 6.3.2 READ_KEYS service action
1063 	 *
1064 	 * Also, when register_move = 1 for PROUT REGISTER_AND_MOVE service
1065 	 * action, the struct se_device->dev_reservation_lock will already be held,
1066 	 * so we do not call core_scsi3_pr_generation() which grabs the lock
1067 	 * for the REGISTER.
1068 	 */
1069 	pr_reg->pr_res_generation = (register_move) ?
1070 			dev->t10_pr.pr_generation++ :
1071 			core_scsi3_pr_generation(dev);
1072 
1073 	spin_lock(&pr_tmpl->registration_lock);
1074 	list_add_tail(&pr_reg->pr_reg_list, &pr_tmpl->registration_list);
1075 
1076 	__core_scsi3_dump_registration(tfo, dev, nacl, pr_reg, register_type);
1077 	spin_unlock(&pr_tmpl->registration_lock);
1078 	/*
1079 	 * Skip extra processing for ALL_TG_PT=0 or REGISTER_AND_MOVE.
1080 	 */
1081 	if (!pr_reg->pr_reg_all_tg_pt || register_move)
1082 		goto out;
1083 	/*
1084 	 * Walk pr_reg->pr_reg_atp_list and add registrations for ALL_TG_PT=1
1085 	 * allocated in __core_scsi3_alloc_registration()
1086 	 */
1087 	list_for_each_entry_safe(pr_reg_tmp, pr_reg_tmp_safe,
1088 			&pr_reg->pr_reg_atp_list, pr_reg_atp_mem_list) {
1089 		struct se_node_acl *nacl_tmp = pr_reg_tmp->pr_reg_nacl;
1090 
1091 		list_del(&pr_reg_tmp->pr_reg_atp_mem_list);
1092 
1093 		pr_reg_tmp->pr_res_generation = core_scsi3_pr_generation(dev);
1094 
1095 		spin_lock(&pr_tmpl->registration_lock);
1096 		list_add_tail(&pr_reg_tmp->pr_reg_list,
1097 			      &pr_tmpl->registration_list);
1098 
1099 		__core_scsi3_dump_registration(tfo, dev, nacl_tmp, pr_reg_tmp,
1100 					       register_type);
1101 		spin_unlock(&pr_tmpl->registration_lock);
1102 		/*
1103 		 * Drop configfs group dependency reference and deve->pr_kref
1104 		 * obtained from  __core_scsi3_alloc_registration() code.
1105 		 */
1106 		rcu_read_lock();
1107 		deve = pr_reg_tmp->pr_reg_deve;
1108 		if (deve) {
1109 			set_bit(DEF_PR_REG_ACTIVE, &deve->deve_flags);
1110 			core_scsi3_lunacl_undepend_item(deve);
1111 			pr_reg_tmp->pr_reg_deve = NULL;
1112 		}
1113 		rcu_read_unlock();
1114 	}
1115 out:
1116 	/*
1117 	 * Drop deve->pr_kref obtained in __core_scsi3_do_alloc_registration()
1118 	 */
1119 	rcu_read_lock();
1120 	deve = pr_reg->pr_reg_deve;
1121 	if (deve) {
1122 		set_bit(DEF_PR_REG_ACTIVE, &deve->deve_flags);
1123 		kref_put(&deve->pr_kref, target_pr_kref_release);
1124 		pr_reg->pr_reg_deve = NULL;
1125 	}
1126 	rcu_read_unlock();
1127 }
1128 
1129 static int core_scsi3_alloc_registration(
1130 	struct se_device *dev,
1131 	struct se_node_acl *nacl,
1132 	struct se_lun *lun,
1133 	struct se_dev_entry *deve,
1134 	u64 mapped_lun,
1135 	unsigned char *isid,
1136 	u64 sa_res_key,
1137 	int all_tg_pt,
1138 	int aptpl,
1139 	enum register_type register_type,
1140 	int register_move)
1141 {
1142 	struct t10_pr_registration *pr_reg;
1143 
1144 	pr_reg = __core_scsi3_alloc_registration(dev, nacl, lun, deve, mapped_lun,
1145 						 isid, sa_res_key, all_tg_pt,
1146 						 aptpl);
1147 	if (!pr_reg)
1148 		return -EPERM;
1149 
1150 	__core_scsi3_add_registration(dev, nacl, pr_reg,
1151 			register_type, register_move);
1152 	return 0;
1153 }
1154 
1155 static struct t10_pr_registration *__core_scsi3_locate_pr_reg(
1156 	struct se_device *dev,
1157 	struct se_node_acl *nacl,
1158 	unsigned char *isid)
1159 {
1160 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
1161 	struct t10_pr_registration *pr_reg, *pr_reg_tmp;
1162 	struct se_portal_group *tpg;
1163 
1164 	spin_lock(&pr_tmpl->registration_lock);
1165 	list_for_each_entry_safe(pr_reg, pr_reg_tmp,
1166 			&pr_tmpl->registration_list, pr_reg_list) {
1167 		/*
1168 		 * First look for a matching struct se_node_acl
1169 		 */
1170 		if (pr_reg->pr_reg_nacl != nacl)
1171 			continue;
1172 
1173 		tpg = pr_reg->pr_reg_nacl->se_tpg;
1174 		/*
1175 		 * If this registration does NOT contain a fabric provided
1176 		 * ISID, then we have found a match.
1177 		 */
1178 		if (!pr_reg->isid_present_at_reg) {
1179 			atomic_inc_mb(&pr_reg->pr_res_holders);
1180 			spin_unlock(&pr_tmpl->registration_lock);
1181 			return pr_reg;
1182 		}
1183 		/*
1184 		 * If the *pr_reg contains a fabric defined ISID for multi-value
1185 		 * SCSI Initiator Port TransportIDs, then we expect a valid
1186 		 * matching ISID to be provided by the local SCSI Initiator Port.
1187 		 */
1188 		if (!isid)
1189 			continue;
1190 		if (strcmp(isid, pr_reg->pr_reg_isid))
1191 			continue;
1192 
1193 		atomic_inc_mb(&pr_reg->pr_res_holders);
1194 		spin_unlock(&pr_tmpl->registration_lock);
1195 		return pr_reg;
1196 	}
1197 	spin_unlock(&pr_tmpl->registration_lock);
1198 
1199 	return NULL;
1200 }
1201 
1202 static struct t10_pr_registration *core_scsi3_locate_pr_reg(
1203 	struct se_device *dev,
1204 	struct se_node_acl *nacl,
1205 	struct se_session *sess)
1206 {
1207 	struct se_portal_group *tpg = nacl->se_tpg;
1208 	unsigned char buf[PR_REG_ISID_LEN], *isid_ptr = NULL;
1209 
1210 	if (tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
1211 		memset(&buf[0], 0, PR_REG_ISID_LEN);
1212 		tpg->se_tpg_tfo->sess_get_initiator_sid(sess, &buf[0],
1213 					PR_REG_ISID_LEN);
1214 		isid_ptr = &buf[0];
1215 	}
1216 
1217 	return __core_scsi3_locate_pr_reg(dev, nacl, isid_ptr);
1218 }
1219 
1220 static void core_scsi3_put_pr_reg(struct t10_pr_registration *pr_reg)
1221 {
1222 	atomic_dec_mb(&pr_reg->pr_res_holders);
1223 }
1224 
1225 static int core_scsi3_check_implicit_release(
1226 	struct se_device *dev,
1227 	struct t10_pr_registration *pr_reg)
1228 {
1229 	struct se_node_acl *nacl = pr_reg->pr_reg_nacl;
1230 	struct t10_pr_registration *pr_res_holder;
1231 	int ret = 0;
1232 
1233 	spin_lock(&dev->dev_reservation_lock);
1234 	pr_res_holder = dev->dev_pr_res_holder;
1235 	if (!pr_res_holder) {
1236 		spin_unlock(&dev->dev_reservation_lock);
1237 		return ret;
1238 	}
1239 	if (pr_res_holder == pr_reg) {
1240 		/*
1241 		 * Perform an implicit RELEASE if the registration that
1242 		 * is being released is holding the reservation.
1243 		 *
1244 		 * From spc4r17, section 5.7.11.1:
1245 		 *
1246 		 * e) If the I_T nexus is the persistent reservation holder
1247 		 *    and the persistent reservation is not an all registrants
1248 		 *    type, then a PERSISTENT RESERVE OUT command with REGISTER
1249 		 *    service action or REGISTER AND  IGNORE EXISTING KEY
1250 		 *    service action with the SERVICE ACTION RESERVATION KEY
1251 		 *    field set to zero (see 5.7.11.3).
1252 		 */
1253 		__core_scsi3_complete_pro_release(dev, nacl, pr_reg, 0, 1);
1254 		ret = 1;
1255 		/*
1256 		 * For 'All Registrants' reservation types, all existing
1257 		 * registrations are still processed as reservation holders
1258 		 * in core_scsi3_pr_seq_non_holder() after the initial
1259 		 * reservation holder is implicitly released here.
1260 		 */
1261 	} else if (pr_reg->pr_reg_all_tg_pt &&
1262 		  (!strcmp(pr_res_holder->pr_reg_nacl->initiatorname,
1263 			  pr_reg->pr_reg_nacl->initiatorname)) &&
1264 		  (pr_res_holder->pr_res_key == pr_reg->pr_res_key)) {
1265 		pr_err("SPC-3 PR: Unable to perform ALL_TG_PT=1"
1266 			" UNREGISTER while existing reservation with matching"
1267 			" key 0x%016Lx is present from another SCSI Initiator"
1268 			" Port\n", pr_reg->pr_res_key);
1269 		ret = -EPERM;
1270 	}
1271 	spin_unlock(&dev->dev_reservation_lock);
1272 
1273 	return ret;
1274 }
1275 
1276 static void __core_scsi3_free_registration(
1277 	struct se_device *dev,
1278 	struct t10_pr_registration *pr_reg,
1279 	struct list_head *preempt_and_abort_list,
1280 	int dec_holders)
1281 	__releases(&pr_tmpl->registration_lock)
1282 	__acquires(&pr_tmpl->registration_lock)
1283 {
1284 	const struct target_core_fabric_ops *tfo =
1285 			pr_reg->pr_reg_nacl->se_tpg->se_tpg_tfo;
1286 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
1287 	struct se_node_acl *nacl = pr_reg->pr_reg_nacl;
1288 	struct se_dev_entry *deve;
1289 	char i_buf[PR_REG_ISID_ID_LEN];
1290 
1291 	lockdep_assert_held(&pr_tmpl->registration_lock);
1292 
1293 	memset(i_buf, 0, PR_REG_ISID_ID_LEN);
1294 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
1295 
1296 	if (!list_empty(&pr_reg->pr_reg_list))
1297 		list_del(&pr_reg->pr_reg_list);
1298 	/*
1299 	 * Caller accessing *pr_reg using core_scsi3_locate_pr_reg(),
1300 	 * so call core_scsi3_put_pr_reg() to decrement our reference.
1301 	 */
1302 	if (dec_holders)
1303 		core_scsi3_put_pr_reg(pr_reg);
1304 
1305 	spin_unlock(&pr_tmpl->registration_lock);
1306 	/*
1307 	 * Wait until all reference from any other I_T nexuses for this
1308 	 * *pr_reg have been released.  Because list_del() is called above,
1309 	 * the last core_scsi3_put_pr_reg(pr_reg) will release this reference
1310 	 * count back to zero, and we release *pr_reg.
1311 	 */
1312 	while (atomic_read(&pr_reg->pr_res_holders) != 0) {
1313 		pr_debug("SPC-3 PR [%s] waiting for pr_res_holders\n",
1314 				tfo->fabric_name);
1315 		cpu_relax();
1316 	}
1317 
1318 	rcu_read_lock();
1319 	deve = target_nacl_find_deve(nacl, pr_reg->pr_res_mapped_lun);
1320 	if (deve)
1321 		clear_bit(DEF_PR_REG_ACTIVE, &deve->deve_flags);
1322 	rcu_read_unlock();
1323 
1324 	spin_lock(&pr_tmpl->registration_lock);
1325 	pr_debug("SPC-3 PR [%s] Service Action: UNREGISTER Initiator"
1326 		" Node: %s%s\n", tfo->fabric_name,
1327 		pr_reg->pr_reg_nacl->initiatorname,
1328 		i_buf);
1329 	pr_debug("SPC-3 PR [%s] for %s TCM Subsystem %s Object Target"
1330 		" Port(s)\n", tfo->fabric_name,
1331 		(pr_reg->pr_reg_all_tg_pt) ? "ALL" : "SINGLE",
1332 		dev->transport->name);
1333 	pr_debug("SPC-3 PR [%s] SA Res Key: 0x%016Lx PRgeneration:"
1334 		" 0x%08x\n", tfo->fabric_name, pr_reg->pr_res_key,
1335 		pr_reg->pr_res_generation);
1336 
1337 	if (!preempt_and_abort_list) {
1338 		pr_reg->pr_reg_deve = NULL;
1339 		pr_reg->pr_reg_nacl = NULL;
1340 		kmem_cache_free(t10_pr_reg_cache, pr_reg);
1341 		return;
1342 	}
1343 	/*
1344 	 * For PREEMPT_AND_ABORT, the list of *pr_reg in preempt_and_abort_list
1345 	 * are released once the ABORT_TASK_SET has completed..
1346 	 */
1347 	list_add_tail(&pr_reg->pr_reg_abort_list, preempt_and_abort_list);
1348 }
1349 
1350 void core_scsi3_free_pr_reg_from_nacl(
1351 	struct se_device *dev,
1352 	struct se_node_acl *nacl)
1353 {
1354 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
1355 	struct t10_pr_registration *pr_reg, *pr_reg_tmp, *pr_res_holder;
1356 	bool free_reg = false;
1357 	/*
1358 	 * If the passed se_node_acl matches the reservation holder,
1359 	 * release the reservation.
1360 	 */
1361 	spin_lock(&dev->dev_reservation_lock);
1362 	pr_res_holder = dev->dev_pr_res_holder;
1363 	if ((pr_res_holder != NULL) &&
1364 	    (pr_res_holder->pr_reg_nacl == nacl)) {
1365 		__core_scsi3_complete_pro_release(dev, nacl, pr_res_holder, 0, 1);
1366 		free_reg = true;
1367 	}
1368 	spin_unlock(&dev->dev_reservation_lock);
1369 	/*
1370 	 * Release any registration associated with the struct se_node_acl.
1371 	 */
1372 	spin_lock(&pr_tmpl->registration_lock);
1373 	if (pr_res_holder && free_reg)
1374 		__core_scsi3_free_registration(dev, pr_res_holder, NULL, 0);
1375 
1376 	list_for_each_entry_safe(pr_reg, pr_reg_tmp,
1377 			&pr_tmpl->registration_list, pr_reg_list) {
1378 
1379 		if (pr_reg->pr_reg_nacl != nacl)
1380 			continue;
1381 
1382 		__core_scsi3_free_registration(dev, pr_reg, NULL, 0);
1383 	}
1384 	spin_unlock(&pr_tmpl->registration_lock);
1385 }
1386 
1387 void core_scsi3_free_all_registrations(
1388 	struct se_device *dev)
1389 {
1390 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
1391 	struct t10_pr_registration *pr_reg, *pr_reg_tmp, *pr_res_holder;
1392 
1393 	spin_lock(&dev->dev_reservation_lock);
1394 	pr_res_holder = dev->dev_pr_res_holder;
1395 	if (pr_res_holder != NULL) {
1396 		struct se_node_acl *pr_res_nacl = pr_res_holder->pr_reg_nacl;
1397 		__core_scsi3_complete_pro_release(dev, pr_res_nacl,
1398 						  pr_res_holder, 0, 0);
1399 	}
1400 	spin_unlock(&dev->dev_reservation_lock);
1401 
1402 	spin_lock(&pr_tmpl->registration_lock);
1403 	list_for_each_entry_safe(pr_reg, pr_reg_tmp,
1404 			&pr_tmpl->registration_list, pr_reg_list) {
1405 
1406 		__core_scsi3_free_registration(dev, pr_reg, NULL, 0);
1407 	}
1408 	spin_unlock(&pr_tmpl->registration_lock);
1409 
1410 	spin_lock(&pr_tmpl->aptpl_reg_lock);
1411 	list_for_each_entry_safe(pr_reg, pr_reg_tmp, &pr_tmpl->aptpl_reg_list,
1412 				pr_reg_aptpl_list) {
1413 		list_del(&pr_reg->pr_reg_aptpl_list);
1414 		kmem_cache_free(t10_pr_reg_cache, pr_reg);
1415 	}
1416 	spin_unlock(&pr_tmpl->aptpl_reg_lock);
1417 }
1418 
1419 static int core_scsi3_tpg_depend_item(struct se_portal_group *tpg)
1420 {
1421 	return target_depend_item(&tpg->tpg_group.cg_item);
1422 }
1423 
1424 static void core_scsi3_tpg_undepend_item(struct se_portal_group *tpg)
1425 {
1426 	target_undepend_item(&tpg->tpg_group.cg_item);
1427 	atomic_dec_mb(&tpg->tpg_pr_ref_count);
1428 }
1429 
1430 static int core_scsi3_nodeacl_depend_item(struct se_node_acl *nacl)
1431 {
1432 	if (nacl->dynamic_node_acl)
1433 		return 0;
1434 	return target_depend_item(&nacl->acl_group.cg_item);
1435 }
1436 
1437 static void core_scsi3_nodeacl_undepend_item(struct se_node_acl *nacl)
1438 {
1439 	if (!nacl->dynamic_node_acl)
1440 		target_undepend_item(&nacl->acl_group.cg_item);
1441 	atomic_dec_mb(&nacl->acl_pr_ref_count);
1442 }
1443 
1444 static int core_scsi3_lunacl_depend_item(struct se_dev_entry *se_deve)
1445 {
1446 	struct se_lun_acl *lun_acl;
1447 
1448 	/*
1449 	 * For nacl->dynamic_node_acl=1
1450 	 */
1451 	lun_acl = rcu_dereference_check(se_deve->se_lun_acl,
1452 				kref_read(&se_deve->pr_kref) != 0);
1453 	if (!lun_acl)
1454 		return 0;
1455 
1456 	return target_depend_item(&lun_acl->se_lun_group.cg_item);
1457 }
1458 
1459 static void core_scsi3_lunacl_undepend_item(struct se_dev_entry *se_deve)
1460 {
1461 	struct se_lun_acl *lun_acl;
1462 
1463 	/*
1464 	 * For nacl->dynamic_node_acl=1
1465 	 */
1466 	lun_acl = rcu_dereference_check(se_deve->se_lun_acl,
1467 				kref_read(&se_deve->pr_kref) != 0);
1468 	if (!lun_acl) {
1469 		kref_put(&se_deve->pr_kref, target_pr_kref_release);
1470 		return;
1471 	}
1472 
1473 	target_undepend_item(&lun_acl->se_lun_group.cg_item);
1474 	kref_put(&se_deve->pr_kref, target_pr_kref_release);
1475 }
1476 
1477 static sense_reason_t
1478 core_scsi3_decode_spec_i_port(
1479 	struct se_cmd *cmd,
1480 	struct se_portal_group *tpg,
1481 	unsigned char *l_isid,
1482 	u64 sa_res_key,
1483 	int all_tg_pt,
1484 	int aptpl)
1485 {
1486 	struct se_device *dev = cmd->se_dev;
1487 	struct se_portal_group *dest_tpg = NULL, *tmp_tpg;
1488 	struct se_session *se_sess = cmd->se_sess;
1489 	struct se_node_acl *dest_node_acl = NULL;
1490 	struct se_dev_entry *dest_se_deve = NULL;
1491 	struct t10_pr_registration *dest_pr_reg, *local_pr_reg, *pr_reg_e;
1492 	struct t10_pr_registration *pr_reg_tmp, *pr_reg_tmp_safe;
1493 	LIST_HEAD(tid_dest_list);
1494 	struct pr_transport_id_holder *tidh_new, *tidh, *tidh_tmp;
1495 	unsigned char *buf, *ptr, proto_ident;
1496 	const unsigned char *i_str = NULL;
1497 	char *iport_ptr = NULL, i_buf[PR_REG_ISID_ID_LEN];
1498 	sense_reason_t ret;
1499 	u32 tpdl, tid_len = 0;
1500 	u32 dest_rtpi = 0;
1501 
1502 	/*
1503 	 * Allocate a struct pr_transport_id_holder and setup the
1504 	 * local_node_acl pointer and add to struct list_head tid_dest_list
1505 	 * for add registration processing in the loop of tid_dest_list below.
1506 	 */
1507 	tidh_new = kzalloc(sizeof(struct pr_transport_id_holder), GFP_KERNEL);
1508 	if (!tidh_new) {
1509 		pr_err("Unable to allocate tidh_new\n");
1510 		return TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
1511 	}
1512 	INIT_LIST_HEAD(&tidh_new->dest_list);
1513 	tidh_new->dest_tpg = tpg;
1514 	tidh_new->dest_node_acl = se_sess->se_node_acl;
1515 
1516 	local_pr_reg = __core_scsi3_alloc_registration(cmd->se_dev,
1517 				se_sess->se_node_acl, cmd->se_lun,
1518 				NULL, cmd->orig_fe_lun, l_isid,
1519 				sa_res_key, all_tg_pt, aptpl);
1520 	if (!local_pr_reg) {
1521 		kfree(tidh_new);
1522 		return TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
1523 	}
1524 	tidh_new->dest_pr_reg = local_pr_reg;
1525 	/*
1526 	 * The local I_T nexus does not hold any configfs dependances,
1527 	 * so we set tidh_new->dest_se_deve to NULL to prevent the
1528 	 * configfs_undepend_item() calls in the tid_dest_list loops below.
1529 	 */
1530 	tidh_new->dest_se_deve = NULL;
1531 	list_add_tail(&tidh_new->dest_list, &tid_dest_list);
1532 
1533 	if (cmd->data_length < 28) {
1534 		pr_warn("SPC-PR: Received PR OUT parameter list"
1535 			" length too small: %u\n", cmd->data_length);
1536 		ret = TCM_INVALID_PARAMETER_LIST;
1537 		goto out;
1538 	}
1539 
1540 	buf = transport_kmap_data_sg(cmd);
1541 	if (!buf) {
1542 		ret = TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
1543 		goto out;
1544 	}
1545 
1546 	/*
1547 	 * For a PERSISTENT RESERVE OUT specify initiator ports payload,
1548 	 * first extract TransportID Parameter Data Length, and make sure
1549 	 * the value matches up to the SCSI expected data transfer length.
1550 	 */
1551 	tpdl = get_unaligned_be32(&buf[24]);
1552 
1553 	if ((tpdl + 28) != cmd->data_length) {
1554 		pr_err("SPC-3 PR: Illegal tpdl: %u + 28 byte header"
1555 			" does not equal CDB data_length: %u\n", tpdl,
1556 			cmd->data_length);
1557 		ret = TCM_INVALID_PARAMETER_LIST;
1558 		goto out_unmap;
1559 	}
1560 	/*
1561 	 * Start processing the received transport IDs using the
1562 	 * receiving I_T Nexus portal's fabric dependent methods to
1563 	 * obtain the SCSI Initiator Port/Device Identifiers.
1564 	 */
1565 	ptr = &buf[28];
1566 
1567 	while (tpdl > 0) {
1568 		struct se_lun *dest_lun, *tmp_lun;
1569 
1570 		proto_ident = (ptr[0] & 0x0f);
1571 		dest_tpg = NULL;
1572 
1573 		spin_lock(&dev->se_port_lock);
1574 		list_for_each_entry(tmp_lun, &dev->dev_sep_list, lun_dev_link) {
1575 			tmp_tpg = tmp_lun->lun_tpg;
1576 
1577 			/*
1578 			 * Look for the matching proto_ident provided by
1579 			 * the received TransportID
1580 			 */
1581 			if (tmp_tpg->proto_id != proto_ident)
1582 				continue;
1583 			dest_rtpi = tmp_lun->lun_rtpi;
1584 
1585 			iport_ptr = NULL;
1586 			i_str = target_parse_pr_out_transport_id(tmp_tpg,
1587 					ptr, &tid_len, &iport_ptr);
1588 			if (!i_str)
1589 				continue;
1590 			/*
1591 			 * Determine if this SCSI device server requires that
1592 			 * SCSI Intiatior TransportID w/ ISIDs is enforced
1593 			 * for fabric modules (iSCSI) requiring them.
1594 			 */
1595 			if (tpg->se_tpg_tfo->sess_get_initiator_sid &&
1596 			    dev->dev_attrib.enforce_pr_isids &&
1597 			    !iport_ptr) {
1598 				pr_warn("SPC-PR: enforce_pr_isids is set but a isid has not been sent in the SPEC_I_PT data for %s.",
1599 					i_str);
1600 				ret = TCM_INVALID_PARAMETER_LIST;
1601 				spin_unlock(&dev->se_port_lock);
1602 				goto out_unmap;
1603 			}
1604 
1605 			atomic_inc_mb(&tmp_tpg->tpg_pr_ref_count);
1606 			spin_unlock(&dev->se_port_lock);
1607 
1608 			if (core_scsi3_tpg_depend_item(tmp_tpg)) {
1609 				pr_err(" core_scsi3_tpg_depend_item()"
1610 					" for tmp_tpg\n");
1611 				atomic_dec_mb(&tmp_tpg->tpg_pr_ref_count);
1612 				ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1613 				goto out_unmap;
1614 			}
1615 			/*
1616 			 * Locate the destination initiator ACL to be registered
1617 			 * from the decoded fabric module specific TransportID
1618 			 * at *i_str.
1619 			 */
1620 			mutex_lock(&tmp_tpg->acl_node_mutex);
1621 			dest_node_acl = __core_tpg_get_initiator_node_acl(
1622 						tmp_tpg, i_str);
1623 			if (dest_node_acl)
1624 				atomic_inc_mb(&dest_node_acl->acl_pr_ref_count);
1625 			mutex_unlock(&tmp_tpg->acl_node_mutex);
1626 
1627 			if (!dest_node_acl) {
1628 				core_scsi3_tpg_undepend_item(tmp_tpg);
1629 				spin_lock(&dev->se_port_lock);
1630 				continue;
1631 			}
1632 
1633 			if (core_scsi3_nodeacl_depend_item(dest_node_acl)) {
1634 				pr_err("configfs_depend_item() failed"
1635 					" for dest_node_acl->acl_group\n");
1636 				atomic_dec_mb(&dest_node_acl->acl_pr_ref_count);
1637 				core_scsi3_tpg_undepend_item(tmp_tpg);
1638 				ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1639 				goto out_unmap;
1640 			}
1641 
1642 			dest_tpg = tmp_tpg;
1643 			pr_debug("SPC-3 PR SPEC_I_PT: Located %s Node:"
1644 				" %s Port RTPI: %hu\n",
1645 				dest_tpg->se_tpg_tfo->fabric_name,
1646 				dest_node_acl->initiatorname, dest_rtpi);
1647 
1648 			spin_lock(&dev->se_port_lock);
1649 			break;
1650 		}
1651 		spin_unlock(&dev->se_port_lock);
1652 
1653 		if (!dest_tpg) {
1654 			pr_err("SPC-3 PR SPEC_I_PT: Unable to locate"
1655 					" dest_tpg\n");
1656 			ret = TCM_INVALID_PARAMETER_LIST;
1657 			goto out_unmap;
1658 		}
1659 
1660 		pr_debug("SPC-3 PR SPEC_I_PT: Got %s data_length: %u tpdl: %u"
1661 			" tid_len: %d for %s + %s\n",
1662 			dest_tpg->se_tpg_tfo->fabric_name, cmd->data_length,
1663 			tpdl, tid_len, i_str, iport_ptr);
1664 
1665 		if (tid_len > tpdl) {
1666 			pr_err("SPC-3 PR SPEC_I_PT: Illegal tid_len:"
1667 				" %u for Transport ID: %s\n", tid_len, ptr);
1668 			core_scsi3_nodeacl_undepend_item(dest_node_acl);
1669 			core_scsi3_tpg_undepend_item(dest_tpg);
1670 			ret = TCM_INVALID_PARAMETER_LIST;
1671 			goto out_unmap;
1672 		}
1673 		/*
1674 		 * Locate the desintation struct se_dev_entry pointer for matching
1675 		 * RELATIVE TARGET PORT IDENTIFIER on the receiving I_T Nexus
1676 		 * Target Port.
1677 		 */
1678 		dest_se_deve = core_get_se_deve_from_rtpi(dest_node_acl,
1679 					dest_rtpi);
1680 		if (!dest_se_deve) {
1681 			pr_err("Unable to locate %s dest_se_deve"
1682 				" from destination RTPI: %hu\n",
1683 				dest_tpg->se_tpg_tfo->fabric_name,
1684 				dest_rtpi);
1685 
1686 			core_scsi3_nodeacl_undepend_item(dest_node_acl);
1687 			core_scsi3_tpg_undepend_item(dest_tpg);
1688 			ret = TCM_INVALID_PARAMETER_LIST;
1689 			goto out_unmap;
1690 		}
1691 
1692 		if (core_scsi3_lunacl_depend_item(dest_se_deve)) {
1693 			pr_err("core_scsi3_lunacl_depend_item()"
1694 					" failed\n");
1695 			kref_put(&dest_se_deve->pr_kref, target_pr_kref_release);
1696 			core_scsi3_nodeacl_undepend_item(dest_node_acl);
1697 			core_scsi3_tpg_undepend_item(dest_tpg);
1698 			ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1699 			goto out_unmap;
1700 		}
1701 
1702 		pr_debug("SPC-3 PR SPEC_I_PT: Located %s Node: %s"
1703 			" dest_se_deve mapped_lun: %llu\n",
1704 			dest_tpg->se_tpg_tfo->fabric_name,
1705 			dest_node_acl->initiatorname, dest_se_deve->mapped_lun);
1706 
1707 		/*
1708 		 * Skip any TransportIDs that already have a registration for
1709 		 * this target port.
1710 		 */
1711 		pr_reg_e = __core_scsi3_locate_pr_reg(dev, dest_node_acl,
1712 					iport_ptr);
1713 		if (pr_reg_e) {
1714 			core_scsi3_put_pr_reg(pr_reg_e);
1715 			core_scsi3_lunacl_undepend_item(dest_se_deve);
1716 			core_scsi3_nodeacl_undepend_item(dest_node_acl);
1717 			core_scsi3_tpg_undepend_item(dest_tpg);
1718 			ptr += tid_len;
1719 			tpdl -= tid_len;
1720 			tid_len = 0;
1721 			continue;
1722 		}
1723 		/*
1724 		 * Allocate a struct pr_transport_id_holder and setup
1725 		 * the dest_node_acl and dest_se_deve pointers for the
1726 		 * loop below.
1727 		 */
1728 		tidh_new = kzalloc(sizeof(struct pr_transport_id_holder),
1729 				GFP_KERNEL);
1730 		if (!tidh_new) {
1731 			pr_err("Unable to allocate tidh_new\n");
1732 			core_scsi3_lunacl_undepend_item(dest_se_deve);
1733 			core_scsi3_nodeacl_undepend_item(dest_node_acl);
1734 			core_scsi3_tpg_undepend_item(dest_tpg);
1735 			ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1736 			goto out_unmap;
1737 		}
1738 		INIT_LIST_HEAD(&tidh_new->dest_list);
1739 		tidh_new->dest_tpg = dest_tpg;
1740 		tidh_new->dest_node_acl = dest_node_acl;
1741 		tidh_new->dest_se_deve = dest_se_deve;
1742 
1743 		/*
1744 		 * Allocate, but do NOT add the registration for the
1745 		 * TransportID referenced SCSI Initiator port.  This
1746 		 * done because of the following from spc4r17 in section
1747 		 * 6.14.3 wrt SPEC_I_PT:
1748 		 *
1749 		 * "If a registration fails for any initiator port (e.g., if th
1750 		 * logical unit does not have enough resources available to
1751 		 * hold the registration information), no registrations shall be
1752 		 * made, and the command shall be terminated with
1753 		 * CHECK CONDITION status."
1754 		 *
1755 		 * That means we call __core_scsi3_alloc_registration() here,
1756 		 * and then call __core_scsi3_add_registration() in the
1757 		 * 2nd loop which will never fail.
1758 		 */
1759 		dest_lun = rcu_dereference_check(dest_se_deve->se_lun,
1760 				kref_read(&dest_se_deve->pr_kref) != 0);
1761 
1762 		dest_pr_reg = __core_scsi3_alloc_registration(cmd->se_dev,
1763 					dest_node_acl, dest_lun, dest_se_deve,
1764 					dest_se_deve->mapped_lun, iport_ptr,
1765 					sa_res_key, all_tg_pt, aptpl);
1766 		if (!dest_pr_reg) {
1767 			core_scsi3_lunacl_undepend_item(dest_se_deve);
1768 			core_scsi3_nodeacl_undepend_item(dest_node_acl);
1769 			core_scsi3_tpg_undepend_item(dest_tpg);
1770 			kfree(tidh_new);
1771 			ret = TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
1772 			goto out_unmap;
1773 		}
1774 		tidh_new->dest_pr_reg = dest_pr_reg;
1775 		list_add_tail(&tidh_new->dest_list, &tid_dest_list);
1776 
1777 		ptr += tid_len;
1778 		tpdl -= tid_len;
1779 		tid_len = 0;
1780 
1781 	}
1782 
1783 	transport_kunmap_data_sg(cmd);
1784 
1785 	/*
1786 	 * Go ahead and create a registrations from tid_dest_list for the
1787 	 * SPEC_I_PT provided TransportID for the *tidh referenced dest_node_acl
1788 	 * and dest_se_deve.
1789 	 *
1790 	 * The SA Reservation Key from the PROUT is set for the
1791 	 * registration, and ALL_TG_PT is also passed.  ALL_TG_PT=1
1792 	 * means that the TransportID Initiator port will be
1793 	 * registered on all of the target ports in the SCSI target device
1794 	 * ALL_TG_PT=0 means the registration will only be for the
1795 	 * SCSI target port the PROUT REGISTER with SPEC_I_PT=1
1796 	 * was received.
1797 	 */
1798 	list_for_each_entry_safe(tidh, tidh_tmp, &tid_dest_list, dest_list) {
1799 		dest_tpg = tidh->dest_tpg;
1800 		dest_node_acl = tidh->dest_node_acl;
1801 		dest_se_deve = tidh->dest_se_deve;
1802 		dest_pr_reg = tidh->dest_pr_reg;
1803 
1804 		list_del(&tidh->dest_list);
1805 		kfree(tidh);
1806 
1807 		memset(i_buf, 0, PR_REG_ISID_ID_LEN);
1808 		core_pr_dump_initiator_port(dest_pr_reg, i_buf, PR_REG_ISID_ID_LEN);
1809 
1810 		__core_scsi3_add_registration(cmd->se_dev, dest_node_acl,
1811 					dest_pr_reg, 0, 0);
1812 
1813 		pr_debug("SPC-3 PR [%s] SPEC_I_PT: Successfully"
1814 			" registered Transport ID for Node: %s%s Mapped LUN:"
1815 			" %llu\n", dest_tpg->se_tpg_tfo->fabric_name,
1816 			dest_node_acl->initiatorname, i_buf, (dest_se_deve) ?
1817 			dest_se_deve->mapped_lun : 0);
1818 
1819 		if (!dest_se_deve) {
1820 			kref_put(&local_pr_reg->pr_reg_deve->pr_kref,
1821 				 target_pr_kref_release);
1822 			continue;
1823 		}
1824 		core_scsi3_lunacl_undepend_item(dest_se_deve);
1825 		core_scsi3_nodeacl_undepend_item(dest_node_acl);
1826 		core_scsi3_tpg_undepend_item(dest_tpg);
1827 	}
1828 
1829 	return 0;
1830 out_unmap:
1831 	transport_kunmap_data_sg(cmd);
1832 out:
1833 	/*
1834 	 * For the failure case, release everything from tid_dest_list
1835 	 * including *dest_pr_reg and the configfs dependances..
1836 	 */
1837 	list_for_each_entry_safe(tidh, tidh_tmp, &tid_dest_list, dest_list) {
1838 		dest_tpg = tidh->dest_tpg;
1839 		dest_node_acl = tidh->dest_node_acl;
1840 		dest_se_deve = tidh->dest_se_deve;
1841 		dest_pr_reg = tidh->dest_pr_reg;
1842 
1843 		list_del(&tidh->dest_list);
1844 		kfree(tidh);
1845 		/*
1846 		 * Release any extra ALL_TG_PT=1 registrations for
1847 		 * the SPEC_I_PT=1 case.
1848 		 */
1849 		list_for_each_entry_safe(pr_reg_tmp, pr_reg_tmp_safe,
1850 				&dest_pr_reg->pr_reg_atp_list,
1851 				pr_reg_atp_mem_list) {
1852 			list_del(&pr_reg_tmp->pr_reg_atp_mem_list);
1853 			core_scsi3_lunacl_undepend_item(pr_reg_tmp->pr_reg_deve);
1854 			kmem_cache_free(t10_pr_reg_cache, pr_reg_tmp);
1855 		}
1856 
1857 		kmem_cache_free(t10_pr_reg_cache, dest_pr_reg);
1858 
1859 		if (!dest_se_deve) {
1860 			kref_put(&local_pr_reg->pr_reg_deve->pr_kref,
1861 				 target_pr_kref_release);
1862 			continue;
1863 		}
1864 		core_scsi3_lunacl_undepend_item(dest_se_deve);
1865 		core_scsi3_nodeacl_undepend_item(dest_node_acl);
1866 		core_scsi3_tpg_undepend_item(dest_tpg);
1867 	}
1868 	return ret;
1869 }
1870 
1871 static int core_scsi3_update_aptpl_buf(
1872 	struct se_device *dev,
1873 	unsigned char *buf,
1874 	u32 pr_aptpl_buf_len)
1875 {
1876 	struct se_portal_group *tpg;
1877 	struct t10_pr_registration *pr_reg;
1878 	unsigned char tmp[512], isid_buf[32];
1879 	ssize_t len = 0;
1880 	int reg_count = 0;
1881 	int ret = 0;
1882 
1883 	spin_lock(&dev->dev_reservation_lock);
1884 	spin_lock(&dev->t10_pr.registration_lock);
1885 	/*
1886 	 * Walk the registration list..
1887 	 */
1888 	list_for_each_entry(pr_reg, &dev->t10_pr.registration_list,
1889 			pr_reg_list) {
1890 
1891 		tmp[0] = '\0';
1892 		isid_buf[0] = '\0';
1893 		tpg = pr_reg->pr_reg_nacl->se_tpg;
1894 		/*
1895 		 * Write out any ISID value to APTPL metadata that was included
1896 		 * in the original registration.
1897 		 */
1898 		if (pr_reg->isid_present_at_reg)
1899 			snprintf(isid_buf, 32, "initiator_sid=%s\n",
1900 					pr_reg->pr_reg_isid);
1901 		/*
1902 		 * Include special metadata if the pr_reg matches the
1903 		 * reservation holder.
1904 		 */
1905 		if (dev->dev_pr_res_holder == pr_reg) {
1906 			snprintf(tmp, 512, "PR_REG_START: %d"
1907 				"\ninitiator_fabric=%s\n"
1908 				"initiator_node=%s\n%s"
1909 				"sa_res_key=%llu\n"
1910 				"res_holder=1\nres_type=%02x\n"
1911 				"res_scope=%02x\nres_all_tg_pt=%d\n"
1912 				"mapped_lun=%llu\n", reg_count,
1913 				tpg->se_tpg_tfo->fabric_name,
1914 				pr_reg->pr_reg_nacl->initiatorname, isid_buf,
1915 				pr_reg->pr_res_key, pr_reg->pr_res_type,
1916 				pr_reg->pr_res_scope, pr_reg->pr_reg_all_tg_pt,
1917 				pr_reg->pr_res_mapped_lun);
1918 		} else {
1919 			snprintf(tmp, 512, "PR_REG_START: %d\n"
1920 				"initiator_fabric=%s\ninitiator_node=%s\n%s"
1921 				"sa_res_key=%llu\nres_holder=0\n"
1922 				"res_all_tg_pt=%d\nmapped_lun=%llu\n",
1923 				reg_count, tpg->se_tpg_tfo->fabric_name,
1924 				pr_reg->pr_reg_nacl->initiatorname, isid_buf,
1925 				pr_reg->pr_res_key, pr_reg->pr_reg_all_tg_pt,
1926 				pr_reg->pr_res_mapped_lun);
1927 		}
1928 
1929 		if ((len + strlen(tmp) >= pr_aptpl_buf_len)) {
1930 			pr_err("Unable to update renaming APTPL metadata,"
1931 			       " reallocating larger buffer\n");
1932 			ret = -EMSGSIZE;
1933 			goto out;
1934 		}
1935 		len += sprintf(buf+len, "%s", tmp);
1936 
1937 		/*
1938 		 * Include information about the associated SCSI target port.
1939 		 */
1940 		snprintf(tmp, 512, "target_fabric=%s\ntarget_node=%s\n"
1941 			"tpgt=%hu\nport_rtpi=%hu\ntarget_lun=%llu\nPR_REG_END:"
1942 			" %d\n", tpg->se_tpg_tfo->fabric_name,
1943 			tpg->se_tpg_tfo->tpg_get_wwn(tpg),
1944 			tpg->se_tpg_tfo->tpg_get_tag(tpg),
1945 			pr_reg->tg_pt_sep_rtpi, pr_reg->pr_aptpl_target_lun,
1946 			reg_count);
1947 
1948 		if ((len + strlen(tmp) >= pr_aptpl_buf_len)) {
1949 			pr_err("Unable to update renaming APTPL metadata,"
1950 			       " reallocating larger buffer\n");
1951 			ret = -EMSGSIZE;
1952 			goto out;
1953 		}
1954 		len += sprintf(buf+len, "%s", tmp);
1955 		reg_count++;
1956 	}
1957 
1958 	if (!reg_count)
1959 		len += sprintf(buf+len, "No Registrations or Reservations");
1960 
1961 out:
1962 	spin_unlock(&dev->t10_pr.registration_lock);
1963 	spin_unlock(&dev->dev_reservation_lock);
1964 
1965 	return ret;
1966 }
1967 
1968 static int __core_scsi3_write_aptpl_to_file(
1969 	struct se_device *dev,
1970 	unsigned char *buf)
1971 {
1972 	struct t10_wwn *wwn = &dev->t10_wwn;
1973 	struct file *file;
1974 	int flags = O_RDWR | O_CREAT | O_TRUNC;
1975 	char *path;
1976 	u32 pr_aptpl_buf_len;
1977 	int ret;
1978 	loff_t pos = 0;
1979 
1980 	path = kasprintf(GFP_KERNEL, "%s/pr/aptpl_%s", db_root,
1981 			&wwn->unit_serial[0]);
1982 	if (!path)
1983 		return -ENOMEM;
1984 
1985 	file = filp_open(path, flags, 0600);
1986 	if (IS_ERR(file)) {
1987 		pr_err("filp_open(%s) for APTPL metadata"
1988 			" failed\n", path);
1989 		kfree(path);
1990 		return PTR_ERR(file);
1991 	}
1992 
1993 	pr_aptpl_buf_len = (strlen(buf) + 1); /* Add extra for NULL */
1994 
1995 	ret = kernel_write(file, buf, pr_aptpl_buf_len, &pos);
1996 
1997 	if (ret < 0)
1998 		pr_debug("Error writing APTPL metadata file: %s\n", path);
1999 	fput(file);
2000 	kfree(path);
2001 
2002 	return (ret < 0) ? -EIO : 0;
2003 }
2004 
2005 /*
2006  * Clear the APTPL metadata if APTPL has been disabled, otherwise
2007  * write out the updated metadata to struct file for this SCSI device.
2008  */
2009 static sense_reason_t core_scsi3_update_and_write_aptpl(struct se_device *dev, bool aptpl)
2010 {
2011 	unsigned char *buf;
2012 	int rc, len = PR_APTPL_BUF_LEN;
2013 
2014 	if (!aptpl) {
2015 		char *null_buf = "No Registrations or Reservations\n";
2016 
2017 		rc = __core_scsi3_write_aptpl_to_file(dev, null_buf);
2018 		dev->t10_pr.pr_aptpl_active = 0;
2019 		pr_debug("SPC-3 PR: Set APTPL Bit Deactivated\n");
2020 
2021 		if (rc)
2022 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2023 
2024 		return 0;
2025 	}
2026 retry:
2027 	buf = vzalloc(len);
2028 	if (!buf)
2029 		return TCM_OUT_OF_RESOURCES;
2030 
2031 	rc = core_scsi3_update_aptpl_buf(dev, buf, len);
2032 	if (rc < 0) {
2033 		vfree(buf);
2034 		len *= 2;
2035 		goto retry;
2036 	}
2037 
2038 	rc = __core_scsi3_write_aptpl_to_file(dev, buf);
2039 	if (rc != 0) {
2040 		pr_err("SPC-3 PR: Could not update APTPL\n");
2041 		vfree(buf);
2042 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2043 	}
2044 	dev->t10_pr.pr_aptpl_active = 1;
2045 	vfree(buf);
2046 	pr_debug("SPC-3 PR: Set APTPL Bit Activated\n");
2047 	return 0;
2048 }
2049 
2050 static sense_reason_t
2051 core_scsi3_emulate_pro_register(struct se_cmd *cmd, u64 res_key, u64 sa_res_key,
2052 		bool aptpl, bool all_tg_pt, bool spec_i_pt, enum register_type register_type)
2053 {
2054 	struct se_session *se_sess = cmd->se_sess;
2055 	struct se_device *dev = cmd->se_dev;
2056 	struct se_lun *se_lun = cmd->se_lun;
2057 	struct se_portal_group *se_tpg;
2058 	struct t10_pr_registration *pr_reg, *pr_reg_p, *pr_reg_tmp;
2059 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
2060 	unsigned char isid_buf[PR_REG_ISID_LEN], *isid_ptr = NULL;
2061 	sense_reason_t ret = TCM_NO_SENSE;
2062 	int pr_holder = 0, type;
2063 
2064 	if (!se_sess || !se_lun) {
2065 		pr_err("SPC-3 PR: se_sess || struct se_lun is NULL!\n");
2066 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2067 	}
2068 	se_tpg = se_sess->se_tpg;
2069 
2070 	if (se_tpg->se_tpg_tfo->sess_get_initiator_sid) {
2071 		memset(&isid_buf[0], 0, PR_REG_ISID_LEN);
2072 		se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess, &isid_buf[0],
2073 				PR_REG_ISID_LEN);
2074 		isid_ptr = &isid_buf[0];
2075 	}
2076 	/*
2077 	 * Follow logic from spc4r17 Section 5.7.7, Register Behaviors Table 47
2078 	 */
2079 	pr_reg = core_scsi3_locate_pr_reg(dev, se_sess->se_node_acl, se_sess);
2080 	if (!pr_reg) {
2081 		if (res_key) {
2082 			pr_warn("SPC-3 PR: Reservation Key non-zero"
2083 				" for SA REGISTER, returning CONFLICT\n");
2084 			return TCM_RESERVATION_CONFLICT;
2085 		}
2086 		/*
2087 		 * Do nothing but return GOOD status.
2088 		 */
2089 		if (!sa_res_key)
2090 			return 0;
2091 
2092 		if (!spec_i_pt) {
2093 			/*
2094 			 * Perform the Service Action REGISTER on the Initiator
2095 			 * Port Endpoint that the PRO was received from on the
2096 			 * Logical Unit of the SCSI device server.
2097 			 */
2098 			if (core_scsi3_alloc_registration(cmd->se_dev,
2099 					se_sess->se_node_acl, cmd->se_lun,
2100 					NULL, cmd->orig_fe_lun, isid_ptr,
2101 					sa_res_key, all_tg_pt, aptpl,
2102 					register_type, 0)) {
2103 				pr_err("Unable to allocate"
2104 					" struct t10_pr_registration\n");
2105 				return TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
2106 			}
2107 		} else {
2108 			/*
2109 			 * Register both the Initiator port that received
2110 			 * PROUT SA REGISTER + SPEC_I_PT=1 and extract SCSI
2111 			 * TransportID from Parameter list and loop through
2112 			 * fabric dependent parameter list while calling
2113 			 * logic from of core_scsi3_alloc_registration() for
2114 			 * each TransportID provided SCSI Initiator Port/Device
2115 			 */
2116 			ret = core_scsi3_decode_spec_i_port(cmd, se_tpg,
2117 					isid_ptr, sa_res_key, all_tg_pt, aptpl);
2118 			if (ret != 0)
2119 				return ret;
2120 		}
2121 		return core_scsi3_update_and_write_aptpl(dev, aptpl);
2122 	}
2123 
2124 	/* ok, existing registration */
2125 
2126 	if ((register_type == REGISTER) && (res_key != pr_reg->pr_res_key)) {
2127 		pr_err("SPC-3 PR REGISTER: Received"
2128 		       " res_key: 0x%016Lx does not match"
2129 		       " existing SA REGISTER res_key:"
2130 		       " 0x%016Lx\n", res_key,
2131 		       pr_reg->pr_res_key);
2132 		ret = TCM_RESERVATION_CONFLICT;
2133 		goto out;
2134 	}
2135 
2136 	if (spec_i_pt) {
2137 		pr_err("SPC-3 PR REGISTER: SPEC_I_PT"
2138 			" set on a registered nexus\n");
2139 		ret = TCM_INVALID_PARAMETER_LIST;
2140 		goto out;
2141 	}
2142 
2143 	/*
2144 	 * An existing ALL_TG_PT=1 registration being released
2145 	 * must also set ALL_TG_PT=1 in the incoming PROUT.
2146 	 */
2147 	if (pr_reg->pr_reg_all_tg_pt && !all_tg_pt) {
2148 		pr_err("SPC-3 PR REGISTER: ALL_TG_PT=1"
2149 			" registration exists, but ALL_TG_PT=1 bit not"
2150 			" present in received PROUT\n");
2151 		ret = TCM_INVALID_CDB_FIELD;
2152 		goto out;
2153 	}
2154 
2155 	/*
2156 	 * sa_res_key=1 Change Reservation Key for registered I_T Nexus.
2157 	 */
2158 	if (sa_res_key) {
2159 		/*
2160 		 * Increment PRgeneration counter for struct se_device"
2161 		 * upon a successful REGISTER, see spc4r17 section 6.3.2
2162 		 * READ_KEYS service action.
2163 		 */
2164 		pr_reg->pr_res_generation = core_scsi3_pr_generation(cmd->se_dev);
2165 		pr_reg->pr_res_key = sa_res_key;
2166 		pr_debug("SPC-3 PR [%s] REGISTER%s: Changed Reservation"
2167 			 " Key for %s to: 0x%016Lx PRgeneration:"
2168 			 " 0x%08x\n", cmd->se_tfo->fabric_name,
2169 			 (register_type == REGISTER_AND_IGNORE_EXISTING_KEY) ? "_AND_IGNORE_EXISTING_KEY" : "",
2170 			 pr_reg->pr_reg_nacl->initiatorname,
2171 			 pr_reg->pr_res_key, pr_reg->pr_res_generation);
2172 
2173 	} else {
2174 		/*
2175 		 * sa_res_key=0 Unregister Reservation Key for registered I_T Nexus.
2176 		 */
2177 		type = pr_reg->pr_res_type;
2178 		pr_holder = core_scsi3_check_implicit_release(cmd->se_dev,
2179 							      pr_reg);
2180 		if (pr_holder < 0) {
2181 			ret = TCM_RESERVATION_CONFLICT;
2182 			goto out;
2183 		}
2184 
2185 		spin_lock(&pr_tmpl->registration_lock);
2186 		/*
2187 		 * Release all ALL_TG_PT=1 for the matching SCSI Initiator Port
2188 		 * and matching pr_res_key.
2189 		 */
2190 		if (pr_reg->pr_reg_all_tg_pt) {
2191 			list_for_each_entry_safe(pr_reg_p, pr_reg_tmp,
2192 					&pr_tmpl->registration_list,
2193 					pr_reg_list) {
2194 
2195 				if (!pr_reg_p->pr_reg_all_tg_pt)
2196 					continue;
2197 				if (pr_reg_p->pr_res_key != res_key)
2198 					continue;
2199 				if (pr_reg == pr_reg_p)
2200 					continue;
2201 				if (strcmp(pr_reg->pr_reg_nacl->initiatorname,
2202 					   pr_reg_p->pr_reg_nacl->initiatorname))
2203 					continue;
2204 
2205 				__core_scsi3_free_registration(dev,
2206 						pr_reg_p, NULL, 0);
2207 			}
2208 		}
2209 
2210 		/*
2211 		 * Release the calling I_T Nexus registration now..
2212 		 */
2213 		__core_scsi3_free_registration(cmd->se_dev, pr_reg, NULL, 1);
2214 		pr_reg = NULL;
2215 
2216 		/*
2217 		 * From spc4r17, section 5.7.11.3 Unregistering
2218 		 *
2219 		 * If the persistent reservation is a registrants only
2220 		 * type, the device server shall establish a unit
2221 		 * attention condition for the initiator port associated
2222 		 * with every registered I_T nexus except for the I_T
2223 		 * nexus on which the PERSISTENT RESERVE OUT command was
2224 		 * received, with the additional sense code set to
2225 		 * RESERVATIONS RELEASED.
2226 		 */
2227 		if (pr_holder &&
2228 		    (type == PR_TYPE_WRITE_EXCLUSIVE_REGONLY ||
2229 		     type == PR_TYPE_EXCLUSIVE_ACCESS_REGONLY)) {
2230 			list_for_each_entry(pr_reg_p,
2231 					&pr_tmpl->registration_list,
2232 					pr_reg_list) {
2233 
2234 				target_ua_allocate_lun(
2235 					pr_reg_p->pr_reg_nacl,
2236 					pr_reg_p->pr_res_mapped_lun,
2237 					0x2A,
2238 					ASCQ_2AH_RESERVATIONS_RELEASED);
2239 			}
2240 		}
2241 
2242 		spin_unlock(&pr_tmpl->registration_lock);
2243 	}
2244 
2245 	ret = core_scsi3_update_and_write_aptpl(dev, aptpl);
2246 
2247 out:
2248 	if (pr_reg)
2249 		core_scsi3_put_pr_reg(pr_reg);
2250 	return ret;
2251 }
2252 
2253 unsigned char *core_scsi3_pr_dump_type(int type)
2254 {
2255 	switch (type) {
2256 	case PR_TYPE_WRITE_EXCLUSIVE:
2257 		return "Write Exclusive Access";
2258 	case PR_TYPE_EXCLUSIVE_ACCESS:
2259 		return "Exclusive Access";
2260 	case PR_TYPE_WRITE_EXCLUSIVE_REGONLY:
2261 		return "Write Exclusive Access, Registrants Only";
2262 	case PR_TYPE_EXCLUSIVE_ACCESS_REGONLY:
2263 		return "Exclusive Access, Registrants Only";
2264 	case PR_TYPE_WRITE_EXCLUSIVE_ALLREG:
2265 		return "Write Exclusive Access, All Registrants";
2266 	case PR_TYPE_EXCLUSIVE_ACCESS_ALLREG:
2267 		return "Exclusive Access, All Registrants";
2268 	default:
2269 		break;
2270 	}
2271 
2272 	return "Unknown SPC-3 PR Type";
2273 }
2274 
2275 static sense_reason_t
2276 core_scsi3_pro_reserve(struct se_cmd *cmd, int type, int scope, u64 res_key)
2277 {
2278 	struct se_device *dev = cmd->se_dev;
2279 	struct se_session *se_sess = cmd->se_sess;
2280 	struct se_lun *se_lun = cmd->se_lun;
2281 	struct t10_pr_registration *pr_reg, *pr_res_holder;
2282 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
2283 	char i_buf[PR_REG_ISID_ID_LEN];
2284 	sense_reason_t ret;
2285 
2286 	memset(i_buf, 0, PR_REG_ISID_ID_LEN);
2287 
2288 	if (!se_sess || !se_lun) {
2289 		pr_err("SPC-3 PR: se_sess || struct se_lun is NULL!\n");
2290 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2291 	}
2292 	/*
2293 	 * Locate the existing *pr_reg via struct se_node_acl pointers
2294 	 */
2295 	pr_reg = core_scsi3_locate_pr_reg(cmd->se_dev, se_sess->se_node_acl,
2296 				se_sess);
2297 	if (!pr_reg) {
2298 		pr_err("SPC-3 PR: Unable to locate"
2299 			" PR_REGISTERED *pr_reg for RESERVE\n");
2300 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2301 	}
2302 	/*
2303 	 * From spc4r17 Section 5.7.9: Reserving:
2304 	 *
2305 	 * An application client creates a persistent reservation by issuing
2306 	 * a PERSISTENT RESERVE OUT command with RESERVE service action through
2307 	 * a registered I_T nexus with the following parameters:
2308 	 *    a) RESERVATION KEY set to the value of the reservation key that is
2309 	 * 	 registered with the logical unit for the I_T nexus; and
2310 	 */
2311 	if (res_key != pr_reg->pr_res_key) {
2312 		pr_err("SPC-3 PR RESERVE: Received res_key: 0x%016Lx"
2313 			" does not match existing SA REGISTER res_key:"
2314 			" 0x%016Lx\n", res_key, pr_reg->pr_res_key);
2315 		ret = TCM_RESERVATION_CONFLICT;
2316 		goto out_put_pr_reg;
2317 	}
2318 	/*
2319 	 * From spc4r17 Section 5.7.9: Reserving:
2320 	 *
2321 	 * From above:
2322 	 *  b) TYPE field and SCOPE field set to the persistent reservation
2323 	 *     being created.
2324 	 *
2325 	 * Only one persistent reservation is allowed at a time per logical unit
2326 	 * and that persistent reservation has a scope of LU_SCOPE.
2327 	 */
2328 	if (scope != PR_SCOPE_LU_SCOPE) {
2329 		pr_err("SPC-3 PR: Illegal SCOPE: 0x%02x\n", scope);
2330 		ret = TCM_INVALID_PARAMETER_LIST;
2331 		goto out_put_pr_reg;
2332 	}
2333 	/*
2334 	 * See if we have an existing PR reservation holder pointer at
2335 	 * struct se_device->dev_pr_res_holder in the form struct t10_pr_registration
2336 	 * *pr_res_holder.
2337 	 */
2338 	spin_lock(&dev->dev_reservation_lock);
2339 	pr_res_holder = dev->dev_pr_res_holder;
2340 	if (pr_res_holder) {
2341 		/*
2342 		 * From spc4r17 Section 5.7.9: Reserving:
2343 		 *
2344 		 * If the device server receives a PERSISTENT RESERVE OUT
2345 		 * command from an I_T nexus other than a persistent reservation
2346 		 * holder (see 5.7.10) that attempts to create a persistent
2347 		 * reservation when a persistent reservation already exists for
2348 		 * the logical unit, then the command shall be completed with
2349 		 * RESERVATION CONFLICT status.
2350 		 */
2351 		if (!is_reservation_holder(pr_res_holder, pr_reg)) {
2352 			struct se_node_acl *pr_res_nacl = pr_res_holder->pr_reg_nacl;
2353 			pr_err("SPC-3 PR: Attempted RESERVE from"
2354 				" [%s]: %s while reservation already held by"
2355 				" [%s]: %s, returning RESERVATION_CONFLICT\n",
2356 				cmd->se_tfo->fabric_name,
2357 				se_sess->se_node_acl->initiatorname,
2358 				pr_res_nacl->se_tpg->se_tpg_tfo->fabric_name,
2359 				pr_res_holder->pr_reg_nacl->initiatorname);
2360 
2361 			spin_unlock(&dev->dev_reservation_lock);
2362 			ret = TCM_RESERVATION_CONFLICT;
2363 			goto out_put_pr_reg;
2364 		}
2365 		/*
2366 		 * From spc4r17 Section 5.7.9: Reserving:
2367 		 *
2368 		 * If a persistent reservation holder attempts to modify the
2369 		 * type or scope of an existing persistent reservation, the
2370 		 * command shall be completed with RESERVATION CONFLICT status.
2371 		 */
2372 		if ((pr_res_holder->pr_res_type != type) ||
2373 		    (pr_res_holder->pr_res_scope != scope)) {
2374 			struct se_node_acl *pr_res_nacl = pr_res_holder->pr_reg_nacl;
2375 			pr_err("SPC-3 PR: Attempted RESERVE from"
2376 				" [%s]: %s trying to change TYPE and/or SCOPE,"
2377 				" while reservation already held by [%s]: %s,"
2378 				" returning RESERVATION_CONFLICT\n",
2379 				cmd->se_tfo->fabric_name,
2380 				se_sess->se_node_acl->initiatorname,
2381 				pr_res_nacl->se_tpg->se_tpg_tfo->fabric_name,
2382 				pr_res_holder->pr_reg_nacl->initiatorname);
2383 
2384 			spin_unlock(&dev->dev_reservation_lock);
2385 			ret = TCM_RESERVATION_CONFLICT;
2386 			goto out_put_pr_reg;
2387 		}
2388 		/*
2389 		 * From spc4r17 Section 5.7.9: Reserving:
2390 		 *
2391 		 * If the device server receives a PERSISTENT RESERVE OUT
2392 		 * command with RESERVE service action where the TYPE field and
2393 		 * the SCOPE field contain the same values as the existing type
2394 		 * and scope from a persistent reservation holder, it shall not
2395 		 * make any change to the existing persistent reservation and
2396 		 * shall completethe command with GOOD status.
2397 		 */
2398 		spin_unlock(&dev->dev_reservation_lock);
2399 		ret = 0;
2400 		goto out_put_pr_reg;
2401 	}
2402 	/*
2403 	 * Otherwise, our *pr_reg becomes the PR reservation holder for said
2404 	 * TYPE/SCOPE.  Also set the received scope and type in *pr_reg.
2405 	 */
2406 	pr_reg->pr_res_scope = scope;
2407 	pr_reg->pr_res_type = type;
2408 	pr_reg->pr_res_holder = 1;
2409 	dev->dev_pr_res_holder = pr_reg;
2410 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
2411 
2412 	pr_debug("SPC-3 PR [%s] Service Action: RESERVE created new"
2413 		" reservation holder TYPE: %s ALL_TG_PT: %d\n",
2414 		cmd->se_tfo->fabric_name, core_scsi3_pr_dump_type(type),
2415 		(pr_reg->pr_reg_all_tg_pt) ? 1 : 0);
2416 	pr_debug("SPC-3 PR [%s] RESERVE Node: %s%s\n",
2417 			cmd->se_tfo->fabric_name,
2418 			se_sess->se_node_acl->initiatorname,
2419 			i_buf);
2420 	spin_unlock(&dev->dev_reservation_lock);
2421 
2422 	if (pr_tmpl->pr_aptpl_active)
2423 		core_scsi3_update_and_write_aptpl(cmd->se_dev, true);
2424 
2425 	ret = 0;
2426 out_put_pr_reg:
2427 	core_scsi3_put_pr_reg(pr_reg);
2428 	return ret;
2429 }
2430 
2431 static sense_reason_t
2432 core_scsi3_emulate_pro_reserve(struct se_cmd *cmd, int type, int scope,
2433 		u64 res_key)
2434 {
2435 	switch (type) {
2436 	case PR_TYPE_WRITE_EXCLUSIVE:
2437 	case PR_TYPE_EXCLUSIVE_ACCESS:
2438 	case PR_TYPE_WRITE_EXCLUSIVE_REGONLY:
2439 	case PR_TYPE_EXCLUSIVE_ACCESS_REGONLY:
2440 	case PR_TYPE_WRITE_EXCLUSIVE_ALLREG:
2441 	case PR_TYPE_EXCLUSIVE_ACCESS_ALLREG:
2442 		return core_scsi3_pro_reserve(cmd, type, scope, res_key);
2443 	default:
2444 		pr_err("SPC-3 PR: Unknown Service Action RESERVE Type:"
2445 			" 0x%02x\n", type);
2446 		return TCM_INVALID_CDB_FIELD;
2447 	}
2448 }
2449 
2450 static void __core_scsi3_complete_pro_release(
2451 	struct se_device *dev,
2452 	struct se_node_acl *se_nacl,
2453 	struct t10_pr_registration *pr_reg,
2454 	int explicit,
2455 	int unreg)
2456 {
2457 	const struct target_core_fabric_ops *tfo = se_nacl->se_tpg->se_tpg_tfo;
2458 	char i_buf[PR_REG_ISID_ID_LEN];
2459 	int pr_res_type = 0, pr_res_scope = 0;
2460 
2461 	lockdep_assert_held(&dev->dev_reservation_lock);
2462 
2463 	memset(i_buf, 0, PR_REG_ISID_ID_LEN);
2464 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
2465 	/*
2466 	 * Go ahead and release the current PR reservation holder.
2467 	 * If an All Registrants reservation is currently active and
2468 	 * a unregister operation is requested, replace the current
2469 	 * dev_pr_res_holder with another active registration.
2470 	 */
2471 	if (dev->dev_pr_res_holder) {
2472 		pr_res_type = dev->dev_pr_res_holder->pr_res_type;
2473 		pr_res_scope = dev->dev_pr_res_holder->pr_res_scope;
2474 		dev->dev_pr_res_holder->pr_res_type = 0;
2475 		dev->dev_pr_res_holder->pr_res_scope = 0;
2476 		dev->dev_pr_res_holder->pr_res_holder = 0;
2477 		dev->dev_pr_res_holder = NULL;
2478 	}
2479 	if (!unreg)
2480 		goto out;
2481 
2482 	spin_lock(&dev->t10_pr.registration_lock);
2483 	list_del_init(&pr_reg->pr_reg_list);
2484 	/*
2485 	 * If the I_T nexus is a reservation holder, the persistent reservation
2486 	 * is of an all registrants type, and the I_T nexus is the last remaining
2487 	 * registered I_T nexus, then the device server shall also release the
2488 	 * persistent reservation.
2489 	 */
2490 	if (!list_empty(&dev->t10_pr.registration_list) &&
2491 	    ((pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG) ||
2492 	     (pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG))) {
2493 		dev->dev_pr_res_holder =
2494 			list_entry(dev->t10_pr.registration_list.next,
2495 				   struct t10_pr_registration, pr_reg_list);
2496 		dev->dev_pr_res_holder->pr_res_type = pr_res_type;
2497 		dev->dev_pr_res_holder->pr_res_scope = pr_res_scope;
2498 		dev->dev_pr_res_holder->pr_res_holder = 1;
2499 	}
2500 	spin_unlock(&dev->t10_pr.registration_lock);
2501 out:
2502 	if (!dev->dev_pr_res_holder) {
2503 		pr_debug("SPC-3 PR [%s] Service Action: %s RELEASE cleared"
2504 			" reservation holder TYPE: %s ALL_TG_PT: %d\n",
2505 			tfo->fabric_name, (explicit) ? "explicit" :
2506 			"implicit", core_scsi3_pr_dump_type(pr_res_type),
2507 			(pr_reg->pr_reg_all_tg_pt) ? 1 : 0);
2508 	}
2509 	pr_debug("SPC-3 PR [%s] RELEASE Node: %s%s\n",
2510 		tfo->fabric_name, se_nacl->initiatorname,
2511 		i_buf);
2512 	/*
2513 	 * Clear TYPE and SCOPE for the next PROUT Service Action: RESERVE
2514 	 */
2515 	pr_reg->pr_res_holder = pr_reg->pr_res_type = pr_reg->pr_res_scope = 0;
2516 }
2517 
2518 static sense_reason_t
2519 core_scsi3_emulate_pro_release(struct se_cmd *cmd, int type, int scope,
2520 		u64 res_key)
2521 {
2522 	struct se_device *dev = cmd->se_dev;
2523 	struct se_session *se_sess = cmd->se_sess;
2524 	struct se_lun *se_lun = cmd->se_lun;
2525 	struct t10_pr_registration *pr_reg, *pr_reg_p, *pr_res_holder;
2526 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
2527 	sense_reason_t ret = 0;
2528 
2529 	if (!se_sess || !se_lun) {
2530 		pr_err("SPC-3 PR: se_sess || struct se_lun is NULL!\n");
2531 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2532 	}
2533 	/*
2534 	 * Locate the existing *pr_reg via struct se_node_acl pointers
2535 	 */
2536 	pr_reg = core_scsi3_locate_pr_reg(dev, se_sess->se_node_acl, se_sess);
2537 	if (!pr_reg) {
2538 		pr_err("SPC-3 PR: Unable to locate"
2539 			" PR_REGISTERED *pr_reg for RELEASE\n");
2540 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2541 	}
2542 	/*
2543 	 * From spc4r17 Section 5.7.11.2 Releasing:
2544 	 *
2545 	 * If there is no persistent reservation or in response to a persistent
2546 	 * reservation release request from a registered I_T nexus that is not a
2547 	 * persistent reservation holder (see 5.7.10), the device server shall
2548 	 * do the following:
2549 	 *
2550 	 *     a) Not release the persistent reservation, if any;
2551 	 *     b) Not remove any registrations; and
2552 	 *     c) Complete the command with GOOD status.
2553 	 */
2554 	spin_lock(&dev->dev_reservation_lock);
2555 	pr_res_holder = dev->dev_pr_res_holder;
2556 	if (!pr_res_holder) {
2557 		/*
2558 		 * No persistent reservation, return GOOD status.
2559 		 */
2560 		spin_unlock(&dev->dev_reservation_lock);
2561 		goto out_put_pr_reg;
2562 	}
2563 
2564 	if (!is_reservation_holder(pr_res_holder, pr_reg)) {
2565 		/*
2566 		 * Release request from a registered I_T nexus that is not a
2567 		 * persistent reservation holder. return GOOD status.
2568 		 */
2569 		spin_unlock(&dev->dev_reservation_lock);
2570 		goto out_put_pr_reg;
2571 	}
2572 
2573 	/*
2574 	 * From spc4r17 Section 5.7.11.2 Releasing:
2575 	 *
2576 	 * Only the persistent reservation holder (see 5.7.10) is allowed to
2577 	 * release a persistent reservation.
2578 	 *
2579 	 * An application client releases the persistent reservation by issuing
2580 	 * a PERSISTENT RESERVE OUT command with RELEASE service action through
2581 	 * an I_T nexus that is a persistent reservation holder with the
2582 	 * following parameters:
2583 	 *
2584 	 *     a) RESERVATION KEY field set to the value of the reservation key
2585 	 *	  that is registered with the logical unit for the I_T nexus;
2586 	 */
2587 	if (res_key != pr_reg->pr_res_key) {
2588 		pr_err("SPC-3 PR RELEASE: Received res_key: 0x%016Lx"
2589 			" does not match existing SA REGISTER res_key:"
2590 			" 0x%016Lx\n", res_key, pr_reg->pr_res_key);
2591 		spin_unlock(&dev->dev_reservation_lock);
2592 		ret = TCM_RESERVATION_CONFLICT;
2593 		goto out_put_pr_reg;
2594 	}
2595 	/*
2596 	 * From spc4r17 Section 5.7.11.2 Releasing and above:
2597 	 *
2598 	 * b) TYPE field and SCOPE field set to match the persistent
2599 	 *    reservation being released.
2600 	 */
2601 	if ((pr_res_holder->pr_res_type != type) ||
2602 	    (pr_res_holder->pr_res_scope != scope)) {
2603 		struct se_node_acl *pr_res_nacl = pr_res_holder->pr_reg_nacl;
2604 		pr_err("SPC-3 PR RELEASE: Attempted to release"
2605 			" reservation from [%s]: %s with different TYPE "
2606 			"and/or SCOPE  while reservation already held by"
2607 			" [%s]: %s, returning RESERVATION_CONFLICT\n",
2608 			cmd->se_tfo->fabric_name,
2609 			se_sess->se_node_acl->initiatorname,
2610 			pr_res_nacl->se_tpg->se_tpg_tfo->fabric_name,
2611 			pr_res_holder->pr_reg_nacl->initiatorname);
2612 
2613 		spin_unlock(&dev->dev_reservation_lock);
2614 		ret = TCM_RESERVATION_CONFLICT;
2615 		goto out_put_pr_reg;
2616 	}
2617 	/*
2618 	 * In response to a persistent reservation release request from the
2619 	 * persistent reservation holder the device server shall perform a
2620 	 * release by doing the following as an uninterrupted series of actions:
2621 	 * a) Release the persistent reservation;
2622 	 * b) Not remove any registration(s);
2623 	 * c) If the released persistent reservation is a registrants only type
2624 	 * or all registrants type persistent reservation,
2625 	 *    the device server shall establish a unit attention condition for
2626 	 *    the initiator port associated with every regis-
2627 	 *    tered I_T nexus other than I_T nexus on which the PERSISTENT
2628 	 *    RESERVE OUT command with RELEASE service action was received,
2629 	 *    with the additional sense code set to RESERVATIONS RELEASED; and
2630 	 * d) If the persistent reservation is of any other type, the device
2631 	 *    server shall not establish a unit attention condition.
2632 	 */
2633 	__core_scsi3_complete_pro_release(dev, se_sess->se_node_acl,
2634 					  pr_reg, 1, 0);
2635 
2636 	spin_unlock(&dev->dev_reservation_lock);
2637 
2638 	if ((type != PR_TYPE_WRITE_EXCLUSIVE_REGONLY) &&
2639 	    (type != PR_TYPE_EXCLUSIVE_ACCESS_REGONLY) &&
2640 	    (type != PR_TYPE_WRITE_EXCLUSIVE_ALLREG) &&
2641 	    (type != PR_TYPE_EXCLUSIVE_ACCESS_ALLREG)) {
2642 		/*
2643 		 * If no UNIT ATTENTION conditions will be established for
2644 		 * PR_TYPE_WRITE_EXCLUSIVE or PR_TYPE_EXCLUSIVE_ACCESS
2645 		 * go ahead and check for APTPL=1 update+write below
2646 		 */
2647 		goto write_aptpl;
2648 	}
2649 
2650 	spin_lock(&pr_tmpl->registration_lock);
2651 	list_for_each_entry(pr_reg_p, &pr_tmpl->registration_list,
2652 			pr_reg_list) {
2653 		/*
2654 		 * Do not establish a UNIT ATTENTION condition
2655 		 * for the calling I_T Nexus
2656 		 */
2657 		if (pr_reg_p == pr_reg)
2658 			continue;
2659 
2660 		target_ua_allocate_lun(pr_reg_p->pr_reg_nacl,
2661 				pr_reg_p->pr_res_mapped_lun,
2662 				0x2A, ASCQ_2AH_RESERVATIONS_RELEASED);
2663 	}
2664 	spin_unlock(&pr_tmpl->registration_lock);
2665 
2666 write_aptpl:
2667 	if (pr_tmpl->pr_aptpl_active)
2668 		core_scsi3_update_and_write_aptpl(cmd->se_dev, true);
2669 
2670 out_put_pr_reg:
2671 	core_scsi3_put_pr_reg(pr_reg);
2672 	return ret;
2673 }
2674 
2675 static sense_reason_t
2676 core_scsi3_emulate_pro_clear(struct se_cmd *cmd, u64 res_key)
2677 {
2678 	struct se_device *dev = cmd->se_dev;
2679 	struct se_node_acl *pr_reg_nacl;
2680 	struct se_session *se_sess = cmd->se_sess;
2681 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
2682 	struct t10_pr_registration *pr_reg, *pr_reg_tmp, *pr_reg_n, *pr_res_holder;
2683 	u64 pr_res_mapped_lun = 0;
2684 	int calling_it_nexus = 0;
2685 	/*
2686 	 * Locate the existing *pr_reg via struct se_node_acl pointers
2687 	 */
2688 	pr_reg_n = core_scsi3_locate_pr_reg(cmd->se_dev,
2689 			se_sess->se_node_acl, se_sess);
2690 	if (!pr_reg_n) {
2691 		pr_err("SPC-3 PR: Unable to locate"
2692 			" PR_REGISTERED *pr_reg for CLEAR\n");
2693 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2694 	}
2695 	/*
2696 	 * From spc4r17 section 5.7.11.6, Clearing:
2697 	 *
2698 	 * Any application client may release the persistent reservation and
2699 	 * remove all registrations from a device server by issuing a
2700 	 * PERSISTENT RESERVE OUT command with CLEAR service action through a
2701 	 * registered I_T nexus with the following parameter:
2702 	 *
2703 	 *	a) RESERVATION KEY field set to the value of the reservation key
2704 	 * 	   that is registered with the logical unit for the I_T nexus.
2705 	 */
2706 	if (res_key != pr_reg_n->pr_res_key) {
2707 		pr_err("SPC-3 PR REGISTER: Received"
2708 			" res_key: 0x%016Lx does not match"
2709 			" existing SA REGISTER res_key:"
2710 			" 0x%016Lx\n", res_key, pr_reg_n->pr_res_key);
2711 		core_scsi3_put_pr_reg(pr_reg_n);
2712 		return TCM_RESERVATION_CONFLICT;
2713 	}
2714 	/*
2715 	 * a) Release the persistent reservation, if any;
2716 	 */
2717 	spin_lock(&dev->dev_reservation_lock);
2718 	pr_res_holder = dev->dev_pr_res_holder;
2719 	if (pr_res_holder) {
2720 		struct se_node_acl *pr_res_nacl = pr_res_holder->pr_reg_nacl;
2721 		__core_scsi3_complete_pro_release(dev, pr_res_nacl,
2722 						  pr_res_holder, 0, 0);
2723 	}
2724 	spin_unlock(&dev->dev_reservation_lock);
2725 	/*
2726 	 * b) Remove all registration(s) (see spc4r17 5.7.7);
2727 	 */
2728 	spin_lock(&pr_tmpl->registration_lock);
2729 	list_for_each_entry_safe(pr_reg, pr_reg_tmp,
2730 			&pr_tmpl->registration_list, pr_reg_list) {
2731 
2732 		calling_it_nexus = (pr_reg_n == pr_reg) ? 1 : 0;
2733 		pr_reg_nacl = pr_reg->pr_reg_nacl;
2734 		pr_res_mapped_lun = pr_reg->pr_res_mapped_lun;
2735 		__core_scsi3_free_registration(dev, pr_reg, NULL,
2736 					calling_it_nexus);
2737 		/*
2738 		 * e) Establish a unit attention condition for the initiator
2739 		 *    port associated with every registered I_T nexus other
2740 		 *    than the I_T nexus on which the PERSISTENT RESERVE OUT
2741 		 *    command with CLEAR service action was received, with the
2742 		 *    additional sense code set to RESERVATIONS PREEMPTED.
2743 		 */
2744 		if (!calling_it_nexus)
2745 			target_ua_allocate_lun(pr_reg_nacl, pr_res_mapped_lun,
2746 				0x2A, ASCQ_2AH_RESERVATIONS_PREEMPTED);
2747 	}
2748 	spin_unlock(&pr_tmpl->registration_lock);
2749 
2750 	pr_debug("SPC-3 PR [%s] Service Action: CLEAR complete\n",
2751 		cmd->se_tfo->fabric_name);
2752 
2753 	core_scsi3_update_and_write_aptpl(cmd->se_dev, false);
2754 
2755 	core_scsi3_pr_generation(dev);
2756 	return 0;
2757 }
2758 
2759 static void __core_scsi3_complete_pro_preempt(
2760 	struct se_device *dev,
2761 	struct t10_pr_registration *pr_reg,
2762 	struct list_head *preempt_and_abort_list,
2763 	int type,
2764 	int scope,
2765 	enum preempt_type preempt_type)
2766 {
2767 	struct se_node_acl *nacl = pr_reg->pr_reg_nacl;
2768 	const struct target_core_fabric_ops *tfo = nacl->se_tpg->se_tpg_tfo;
2769 	char i_buf[PR_REG_ISID_ID_LEN];
2770 
2771 	lockdep_assert_held(&dev->dev_reservation_lock);
2772 
2773 	memset(i_buf, 0, PR_REG_ISID_ID_LEN);
2774 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
2775 	/*
2776 	 * Do an implicit RELEASE of the existing reservation.
2777 	 */
2778 	if (dev->dev_pr_res_holder)
2779 		__core_scsi3_complete_pro_release(dev, nacl,
2780 						  dev->dev_pr_res_holder, 0, 0);
2781 
2782 	dev->dev_pr_res_holder = pr_reg;
2783 	pr_reg->pr_res_holder = 1;
2784 	pr_reg->pr_res_type = type;
2785 	pr_reg->pr_res_scope = scope;
2786 
2787 	pr_debug("SPC-3 PR [%s] Service Action: PREEMPT%s created new"
2788 		" reservation holder TYPE: %s ALL_TG_PT: %d\n",
2789 		tfo->fabric_name, (preempt_type == PREEMPT_AND_ABORT) ? "_AND_ABORT" : "",
2790 		core_scsi3_pr_dump_type(type),
2791 		(pr_reg->pr_reg_all_tg_pt) ? 1 : 0);
2792 	pr_debug("SPC-3 PR [%s] PREEMPT%s from Node: %s%s\n",
2793 		tfo->fabric_name, (preempt_type == PREEMPT_AND_ABORT) ? "_AND_ABORT" : "",
2794 		nacl->initiatorname, i_buf);
2795 	/*
2796 	 * For PREEMPT_AND_ABORT, add the preempting reservation's
2797 	 * struct t10_pr_registration to the list that will be compared
2798 	 * against received CDBs..
2799 	 */
2800 	if (preempt_and_abort_list)
2801 		list_add_tail(&pr_reg->pr_reg_abort_list,
2802 				preempt_and_abort_list);
2803 }
2804 
2805 static void core_scsi3_release_preempt_and_abort(
2806 	struct list_head *preempt_and_abort_list,
2807 	struct t10_pr_registration *pr_reg_holder)
2808 {
2809 	struct t10_pr_registration *pr_reg, *pr_reg_tmp;
2810 
2811 	list_for_each_entry_safe(pr_reg, pr_reg_tmp, preempt_and_abort_list,
2812 				pr_reg_abort_list) {
2813 
2814 		list_del(&pr_reg->pr_reg_abort_list);
2815 		if (pr_reg_holder == pr_reg)
2816 			continue;
2817 		if (pr_reg->pr_res_holder) {
2818 			pr_warn("pr_reg->pr_res_holder still set\n");
2819 			continue;
2820 		}
2821 
2822 		pr_reg->pr_reg_deve = NULL;
2823 		pr_reg->pr_reg_nacl = NULL;
2824 		kmem_cache_free(t10_pr_reg_cache, pr_reg);
2825 	}
2826 }
2827 
2828 static sense_reason_t
2829 core_scsi3_pro_preempt(struct se_cmd *cmd, int type, int scope, u64 res_key,
2830 		u64 sa_res_key, enum preempt_type preempt_type)
2831 {
2832 	struct se_device *dev = cmd->se_dev;
2833 	struct se_node_acl *pr_reg_nacl;
2834 	struct se_session *se_sess = cmd->se_sess;
2835 	LIST_HEAD(preempt_and_abort_list);
2836 	struct t10_pr_registration *pr_reg, *pr_reg_tmp, *pr_reg_n, *pr_res_holder;
2837 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
2838 	u64 pr_res_mapped_lun = 0;
2839 	int all_reg = 0, calling_it_nexus = 0;
2840 	bool sa_res_key_unmatched = sa_res_key != 0;
2841 	int prh_type = 0, prh_scope = 0;
2842 
2843 	if (!se_sess)
2844 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2845 
2846 	pr_reg_n = core_scsi3_locate_pr_reg(cmd->se_dev, se_sess->se_node_acl,
2847 				se_sess);
2848 	if (!pr_reg_n) {
2849 		pr_err("SPC-3 PR: Unable to locate"
2850 			" PR_REGISTERED *pr_reg for PREEMPT%s\n",
2851 			(preempt_type == PREEMPT_AND_ABORT) ? "_AND_ABORT" : "");
2852 		return TCM_RESERVATION_CONFLICT;
2853 	}
2854 	if (pr_reg_n->pr_res_key != res_key) {
2855 		core_scsi3_put_pr_reg(pr_reg_n);
2856 		return TCM_RESERVATION_CONFLICT;
2857 	}
2858 	if (scope != PR_SCOPE_LU_SCOPE) {
2859 		pr_err("SPC-3 PR: Illegal SCOPE: 0x%02x\n", scope);
2860 		core_scsi3_put_pr_reg(pr_reg_n);
2861 		return TCM_INVALID_PARAMETER_LIST;
2862 	}
2863 
2864 	spin_lock(&dev->dev_reservation_lock);
2865 	pr_res_holder = dev->dev_pr_res_holder;
2866 	if (pr_res_holder &&
2867 	   ((pr_res_holder->pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG) ||
2868 	    (pr_res_holder->pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG)))
2869 		all_reg = 1;
2870 
2871 	if (!all_reg && !sa_res_key) {
2872 		spin_unlock(&dev->dev_reservation_lock);
2873 		core_scsi3_put_pr_reg(pr_reg_n);
2874 		return TCM_INVALID_PARAMETER_LIST;
2875 	}
2876 	/*
2877 	 * From spc4r17, section 5.7.11.4.4 Removing Registrations:
2878 	 *
2879 	 * If the SERVICE ACTION RESERVATION KEY field does not identify a
2880 	 * persistent reservation holder or there is no persistent reservation
2881 	 * holder (i.e., there is no persistent reservation), then the device
2882 	 * server shall perform a preempt by doing the following in an
2883 	 * uninterrupted series of actions. (See below..)
2884 	 */
2885 	if (!pr_res_holder || (pr_res_holder->pr_res_key != sa_res_key)) {
2886 		/*
2887 		 * No existing or SA Reservation Key matching reservations..
2888 		 *
2889 		 * PROUT SA PREEMPT with All Registrant type reservations are
2890 		 * allowed to be processed without a matching SA Reservation Key
2891 		 */
2892 		spin_lock(&pr_tmpl->registration_lock);
2893 		list_for_each_entry_safe(pr_reg, pr_reg_tmp,
2894 				&pr_tmpl->registration_list, pr_reg_list) {
2895 			/*
2896 			 * Removing of registrations in non all registrants
2897 			 * type reservations without a matching SA reservation
2898 			 * key.
2899 			 *
2900 			 * a) Remove the registrations for all I_T nexuses
2901 			 *    specified by the SERVICE ACTION RESERVATION KEY
2902 			 *    field;
2903 			 * b) Ignore the contents of the SCOPE and TYPE fields;
2904 			 * c) Process tasks as defined in 5.7.1; and
2905 			 * d) Establish a unit attention condition for the
2906 			 *    initiator port associated with every I_T nexus
2907 			 *    that lost its registration other than the I_T
2908 			 *    nexus on which the PERSISTENT RESERVE OUT command
2909 			 *    was received, with the additional sense code set
2910 			 *    to REGISTRATIONS PREEMPTED.
2911 			 */
2912 			if (!all_reg) {
2913 				if (pr_reg->pr_res_key != sa_res_key)
2914 					continue;
2915 				sa_res_key_unmatched = false;
2916 
2917 				calling_it_nexus = (pr_reg_n == pr_reg) ? 1 : 0;
2918 				pr_reg_nacl = pr_reg->pr_reg_nacl;
2919 				pr_res_mapped_lun = pr_reg->pr_res_mapped_lun;
2920 				__core_scsi3_free_registration(dev, pr_reg,
2921 					(preempt_type == PREEMPT_AND_ABORT) ? &preempt_and_abort_list :
2922 						NULL, calling_it_nexus);
2923 			} else {
2924 				/*
2925 				 * Case for any existing all registrants type
2926 				 * reservation, follow logic in spc4r17 section
2927 				 * 5.7.11.4 Preempting, Table 52 and Figure 7.
2928 				 *
2929 				 * For a ZERO SA Reservation key, release
2930 				 * all other registrations and do an implicit
2931 				 * release of active persistent reservation.
2932 				 *
2933 				 * For a non-ZERO SA Reservation key, only
2934 				 * release the matching reservation key from
2935 				 * registrations.
2936 				 */
2937 				if ((sa_res_key) &&
2938 				     (pr_reg->pr_res_key != sa_res_key))
2939 					continue;
2940 				sa_res_key_unmatched = false;
2941 
2942 				calling_it_nexus = (pr_reg_n == pr_reg) ? 1 : 0;
2943 				if (calling_it_nexus)
2944 					continue;
2945 
2946 				pr_reg_nacl = pr_reg->pr_reg_nacl;
2947 				pr_res_mapped_lun = pr_reg->pr_res_mapped_lun;
2948 				__core_scsi3_free_registration(dev, pr_reg,
2949 					(preempt_type == PREEMPT_AND_ABORT) ? &preempt_and_abort_list :
2950 						NULL, 0);
2951 			}
2952 			if (!calling_it_nexus)
2953 				target_ua_allocate_lun(pr_reg_nacl,
2954 					pr_res_mapped_lun, 0x2A,
2955 					ASCQ_2AH_REGISTRATIONS_PREEMPTED);
2956 		}
2957 		spin_unlock(&pr_tmpl->registration_lock);
2958 		/*
2959 		 * If a PERSISTENT RESERVE OUT with a PREEMPT service action or
2960 		 * a PREEMPT AND ABORT service action sets the SERVICE ACTION
2961 		 * RESERVATION KEY field to a value that does not match any
2962 		 * registered reservation key, then the device server shall
2963 		 * complete the command with RESERVATION CONFLICT status.
2964 		 */
2965 		if (sa_res_key_unmatched) {
2966 			spin_unlock(&dev->dev_reservation_lock);
2967 			core_scsi3_put_pr_reg(pr_reg_n);
2968 			return TCM_RESERVATION_CONFLICT;
2969 		}
2970 		/*
2971 		 * For an existing all registrants type reservation
2972 		 * with a zero SA rservation key, preempt the existing
2973 		 * reservation with the new PR type and scope.
2974 		 */
2975 		if (pr_res_holder && all_reg && !(sa_res_key)) {
2976 			__core_scsi3_complete_pro_preempt(dev, pr_reg_n,
2977 				(preempt_type == PREEMPT_AND_ABORT) ? &preempt_and_abort_list : NULL,
2978 				type, scope, preempt_type);
2979 
2980 			if (preempt_type == PREEMPT_AND_ABORT)
2981 				core_scsi3_release_preempt_and_abort(
2982 					&preempt_and_abort_list, pr_reg_n);
2983 		}
2984 		spin_unlock(&dev->dev_reservation_lock);
2985 
2986 		if (pr_tmpl->pr_aptpl_active)
2987 			core_scsi3_update_and_write_aptpl(cmd->se_dev, true);
2988 
2989 		core_scsi3_put_pr_reg(pr_reg_n);
2990 		core_scsi3_pr_generation(cmd->se_dev);
2991 		return 0;
2992 	}
2993 	/*
2994 	 * The PREEMPTing SA reservation key matches that of the
2995 	 * existing persistent reservation, first, we check if
2996 	 * we are preempting our own reservation.
2997 	 * From spc4r17, section 5.7.11.4.3 Preempting
2998 	 * persistent reservations and registration handling
2999 	 *
3000 	 * If an all registrants persistent reservation is not
3001 	 * present, it is not an error for the persistent
3002 	 * reservation holder to preempt itself (i.e., a
3003 	 * PERSISTENT RESERVE OUT with a PREEMPT service action
3004 	 * or a PREEMPT AND ABORT service action with the
3005 	 * SERVICE ACTION RESERVATION KEY value equal to the
3006 	 * persistent reservation holder's reservation key that
3007 	 * is received from the persistent reservation holder).
3008 	 * In that case, the device server shall establish the
3009 	 * new persistent reservation and maintain the
3010 	 * registration.
3011 	 */
3012 	prh_type = pr_res_holder->pr_res_type;
3013 	prh_scope = pr_res_holder->pr_res_scope;
3014 	/*
3015 	 * If the SERVICE ACTION RESERVATION KEY field identifies a
3016 	 * persistent reservation holder (see 5.7.10), the device
3017 	 * server shall perform a preempt by doing the following as
3018 	 * an uninterrupted series of actions:
3019 	 *
3020 	 * a) Release the persistent reservation for the holder
3021 	 *    identified by the SERVICE ACTION RESERVATION KEY field;
3022 	 */
3023 	if (pr_reg_n != pr_res_holder)
3024 		__core_scsi3_complete_pro_release(dev,
3025 						  pr_res_holder->pr_reg_nacl,
3026 						  dev->dev_pr_res_holder, 0, 0);
3027 	/*
3028 	 * b) Remove the registrations for all I_T nexuses identified
3029 	 *    by the SERVICE ACTION RESERVATION KEY field, except the
3030 	 *    I_T nexus that is being used for the PERSISTENT RESERVE
3031 	 *    OUT command. If an all registrants persistent reservation
3032 	 *    is present and the SERVICE ACTION RESERVATION KEY field
3033 	 *    is set to zero, then all registrations shall be removed
3034 	 *    except for that of the I_T nexus that is being used for
3035 	 *    the PERSISTENT RESERVE OUT command;
3036 	 */
3037 	spin_lock(&pr_tmpl->registration_lock);
3038 	list_for_each_entry_safe(pr_reg, pr_reg_tmp,
3039 			&pr_tmpl->registration_list, pr_reg_list) {
3040 
3041 		calling_it_nexus = (pr_reg_n == pr_reg) ? 1 : 0;
3042 		if (calling_it_nexus)
3043 			continue;
3044 
3045 		if (pr_reg->pr_res_key != sa_res_key)
3046 			continue;
3047 
3048 		pr_reg_nacl = pr_reg->pr_reg_nacl;
3049 		pr_res_mapped_lun = pr_reg->pr_res_mapped_lun;
3050 		__core_scsi3_free_registration(dev, pr_reg,
3051 				(preempt_type == PREEMPT_AND_ABORT) ? &preempt_and_abort_list : NULL,
3052 				calling_it_nexus);
3053 		/*
3054 		 * e) Establish a unit attention condition for the initiator
3055 		 *    port associated with every I_T nexus that lost its
3056 		 *    persistent reservation and/or registration, with the
3057 		 *    additional sense code set to REGISTRATIONS PREEMPTED;
3058 		 */
3059 		target_ua_allocate_lun(pr_reg_nacl, pr_res_mapped_lun, 0x2A,
3060 				ASCQ_2AH_REGISTRATIONS_PREEMPTED);
3061 	}
3062 	spin_unlock(&pr_tmpl->registration_lock);
3063 	/*
3064 	 * c) Establish a persistent reservation for the preempting
3065 	 *    I_T nexus using the contents of the SCOPE and TYPE fields;
3066 	 */
3067 	__core_scsi3_complete_pro_preempt(dev, pr_reg_n,
3068 			(preempt_type == PREEMPT_AND_ABORT) ? &preempt_and_abort_list : NULL,
3069 			type, scope, preempt_type);
3070 	/*
3071 	 * d) Process tasks as defined in 5.7.1;
3072 	 * e) See above..
3073 	 * f) If the type or scope has changed, then for every I_T nexus
3074 	 *    whose reservation key was not removed, except for the I_T
3075 	 *    nexus on which the PERSISTENT RESERVE OUT command was
3076 	 *    received, the device server shall establish a unit
3077 	 *    attention condition for the initiator port associated with
3078 	 *    that I_T nexus, with the additional sense code set to
3079 	 *    RESERVATIONS RELEASED. If the type or scope have not
3080 	 *    changed, then no unit attention condition(s) shall be
3081 	 *    established for this reason.
3082 	 */
3083 	if ((prh_type != type) || (prh_scope != scope)) {
3084 		spin_lock(&pr_tmpl->registration_lock);
3085 		list_for_each_entry_safe(pr_reg, pr_reg_tmp,
3086 				&pr_tmpl->registration_list, pr_reg_list) {
3087 
3088 			calling_it_nexus = (pr_reg_n == pr_reg) ? 1 : 0;
3089 			if (calling_it_nexus)
3090 				continue;
3091 
3092 			target_ua_allocate_lun(pr_reg->pr_reg_nacl,
3093 					pr_reg->pr_res_mapped_lun, 0x2A,
3094 					ASCQ_2AH_RESERVATIONS_RELEASED);
3095 		}
3096 		spin_unlock(&pr_tmpl->registration_lock);
3097 	}
3098 	spin_unlock(&dev->dev_reservation_lock);
3099 	/*
3100 	 * Call LUN_RESET logic upon list of struct t10_pr_registration,
3101 	 * All received CDBs for the matching existing reservation and
3102 	 * registrations undergo ABORT_TASK logic.
3103 	 *
3104 	 * From there, core_scsi3_release_preempt_and_abort() will
3105 	 * release every registration in the list (which have already
3106 	 * been removed from the primary pr_reg list), except the
3107 	 * new persistent reservation holder, the calling Initiator Port.
3108 	 */
3109 	if (preempt_type == PREEMPT_AND_ABORT) {
3110 		core_tmr_lun_reset(dev, NULL, &preempt_and_abort_list, cmd);
3111 		core_scsi3_release_preempt_and_abort(&preempt_and_abort_list,
3112 						pr_reg_n);
3113 	}
3114 
3115 	if (pr_tmpl->pr_aptpl_active)
3116 		core_scsi3_update_and_write_aptpl(cmd->se_dev, true);
3117 
3118 	core_scsi3_put_pr_reg(pr_reg_n);
3119 	core_scsi3_pr_generation(cmd->se_dev);
3120 	return 0;
3121 }
3122 
3123 static sense_reason_t
3124 core_scsi3_emulate_pro_preempt(struct se_cmd *cmd, int type, int scope,
3125 		u64 res_key, u64 sa_res_key, enum preempt_type preempt_type)
3126 {
3127 	switch (type) {
3128 	case PR_TYPE_WRITE_EXCLUSIVE:
3129 	case PR_TYPE_EXCLUSIVE_ACCESS:
3130 	case PR_TYPE_WRITE_EXCLUSIVE_REGONLY:
3131 	case PR_TYPE_EXCLUSIVE_ACCESS_REGONLY:
3132 	case PR_TYPE_WRITE_EXCLUSIVE_ALLREG:
3133 	case PR_TYPE_EXCLUSIVE_ACCESS_ALLREG:
3134 		return core_scsi3_pro_preempt(cmd, type, scope, res_key,
3135 					      sa_res_key, preempt_type);
3136 	default:
3137 		pr_err("SPC-3 PR: Unknown Service Action PREEMPT%s"
3138 			" Type: 0x%02x\n", (preempt_type == PREEMPT_AND_ABORT) ? "_AND_ABORT" : "", type);
3139 		return TCM_INVALID_CDB_FIELD;
3140 	}
3141 }
3142 
3143 
3144 static sense_reason_t
3145 core_scsi3_emulate_pro_register_and_move(struct se_cmd *cmd, u64 res_key,
3146 		u64 sa_res_key, int aptpl, int unreg)
3147 {
3148 	struct se_session *se_sess = cmd->se_sess;
3149 	struct se_device *dev = cmd->se_dev;
3150 	struct se_dev_entry *dest_se_deve = NULL;
3151 	struct se_lun *se_lun = cmd->se_lun, *tmp_lun;
3152 	struct se_node_acl *pr_res_nacl, *pr_reg_nacl, *dest_node_acl = NULL;
3153 	struct se_portal_group *se_tpg, *dest_se_tpg = NULL;
3154 	const struct target_core_fabric_ops *dest_tf_ops = NULL, *tf_ops;
3155 	struct t10_pr_registration *pr_reg, *pr_res_holder, *dest_pr_reg;
3156 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
3157 	unsigned char *buf;
3158 	const unsigned char *initiator_str;
3159 	char *iport_ptr = NULL, i_buf[PR_REG_ISID_ID_LEN];
3160 	u32 tid_len, tmp_tid_len;
3161 	int new_reg = 0, type, scope, matching_iname;
3162 	sense_reason_t ret;
3163 	unsigned short rtpi;
3164 	unsigned char proto_ident;
3165 
3166 	if (!se_sess || !se_lun) {
3167 		pr_err("SPC-3 PR: se_sess || struct se_lun is NULL!\n");
3168 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3169 	}
3170 
3171 	memset(i_buf, 0, PR_REG_ISID_ID_LEN);
3172 	se_tpg = se_sess->se_tpg;
3173 	tf_ops = se_tpg->se_tpg_tfo;
3174 	/*
3175 	 * Follow logic from spc4r17 Section 5.7.8, Table 50 --
3176 	 *	Register behaviors for a REGISTER AND MOVE service action
3177 	 *
3178 	 * Locate the existing *pr_reg via struct se_node_acl pointers
3179 	 */
3180 	pr_reg = core_scsi3_locate_pr_reg(cmd->se_dev, se_sess->se_node_acl,
3181 				se_sess);
3182 	if (!pr_reg) {
3183 		pr_err("SPC-3 PR: Unable to locate PR_REGISTERED"
3184 			" *pr_reg for REGISTER_AND_MOVE\n");
3185 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3186 	}
3187 	/*
3188 	 * The provided reservation key much match the existing reservation key
3189 	 * provided during this initiator's I_T nexus registration.
3190 	 */
3191 	if (res_key != pr_reg->pr_res_key) {
3192 		pr_warn("SPC-3 PR REGISTER_AND_MOVE: Received"
3193 			" res_key: 0x%016Lx does not match existing SA REGISTER"
3194 			" res_key: 0x%016Lx\n", res_key, pr_reg->pr_res_key);
3195 		ret = TCM_RESERVATION_CONFLICT;
3196 		goto out_put_pr_reg;
3197 	}
3198 	/*
3199 	 * The service active reservation key needs to be non zero
3200 	 */
3201 	if (!sa_res_key) {
3202 		pr_warn("SPC-3 PR REGISTER_AND_MOVE: Received zero"
3203 			" sa_res_key\n");
3204 		ret = TCM_INVALID_PARAMETER_LIST;
3205 		goto out_put_pr_reg;
3206 	}
3207 
3208 	/*
3209 	 * Determine the Relative Target Port Identifier where the reservation
3210 	 * will be moved to for the TransportID containing SCSI initiator WWN
3211 	 * information.
3212 	 */
3213 	buf = transport_kmap_data_sg(cmd);
3214 	if (!buf) {
3215 		ret = TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
3216 		goto out_put_pr_reg;
3217 	}
3218 
3219 	rtpi = get_unaligned_be16(&buf[18]);
3220 	tid_len = get_unaligned_be32(&buf[20]);
3221 	transport_kunmap_data_sg(cmd);
3222 	buf = NULL;
3223 
3224 	if ((tid_len + 24) != cmd->data_length) {
3225 		pr_err("SPC-3 PR: Illegal tid_len: %u + 24 byte header"
3226 			" does not equal CDB data_length: %u\n", tid_len,
3227 			cmd->data_length);
3228 		ret = TCM_INVALID_PARAMETER_LIST;
3229 		goto out_put_pr_reg;
3230 	}
3231 
3232 	spin_lock(&dev->se_port_lock);
3233 	list_for_each_entry(tmp_lun, &dev->dev_sep_list, lun_dev_link) {
3234 		if (tmp_lun->lun_rtpi != rtpi)
3235 			continue;
3236 		dest_se_tpg = tmp_lun->lun_tpg;
3237 		dest_tf_ops = dest_se_tpg->se_tpg_tfo;
3238 		if (!dest_tf_ops)
3239 			continue;
3240 
3241 		atomic_inc_mb(&dest_se_tpg->tpg_pr_ref_count);
3242 		spin_unlock(&dev->se_port_lock);
3243 
3244 		if (core_scsi3_tpg_depend_item(dest_se_tpg)) {
3245 			pr_err("core_scsi3_tpg_depend_item() failed"
3246 				" for dest_se_tpg\n");
3247 			atomic_dec_mb(&dest_se_tpg->tpg_pr_ref_count);
3248 			ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3249 			goto out_put_pr_reg;
3250 		}
3251 
3252 		spin_lock(&dev->se_port_lock);
3253 		break;
3254 	}
3255 	spin_unlock(&dev->se_port_lock);
3256 
3257 	if (!dest_se_tpg || !dest_tf_ops) {
3258 		pr_err("SPC-3 PR REGISTER_AND_MOVE: Unable to locate"
3259 			" fabric ops from Relative Target Port Identifier:"
3260 			" %hu\n", rtpi);
3261 		ret = TCM_INVALID_PARAMETER_LIST;
3262 		goto out_put_pr_reg;
3263 	}
3264 
3265 	buf = transport_kmap_data_sg(cmd);
3266 	if (!buf) {
3267 		ret = TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
3268 		goto out_put_pr_reg;
3269 	}
3270 	proto_ident = (buf[24] & 0x0f);
3271 
3272 	pr_debug("SPC-3 PR REGISTER_AND_MOVE: Extracted Protocol Identifier:"
3273 			" 0x%02x\n", proto_ident);
3274 
3275 	if (proto_ident != dest_se_tpg->proto_id) {
3276 		pr_err("SPC-3 PR REGISTER_AND_MOVE: Received"
3277 			" proto_ident: 0x%02x does not match ident: 0x%02x"
3278 			" from fabric: %s\n", proto_ident,
3279 			dest_se_tpg->proto_id,
3280 			dest_tf_ops->fabric_name);
3281 		ret = TCM_INVALID_PARAMETER_LIST;
3282 		goto out;
3283 	}
3284 	initiator_str = target_parse_pr_out_transport_id(dest_se_tpg,
3285 			&buf[24], &tmp_tid_len, &iport_ptr);
3286 	if (!initiator_str) {
3287 		pr_err("SPC-3 PR REGISTER_AND_MOVE: Unable to locate"
3288 			" initiator_str from Transport ID\n");
3289 		ret = TCM_INVALID_PARAMETER_LIST;
3290 		goto out;
3291 	}
3292 
3293 	transport_kunmap_data_sg(cmd);
3294 	buf = NULL;
3295 
3296 	pr_debug("SPC-3 PR [%s] Extracted initiator %s identifier: %s"
3297 		" %s\n", dest_tf_ops->fabric_name, (iport_ptr != NULL) ?
3298 		"port" : "device", initiator_str, (iport_ptr != NULL) ?
3299 		iport_ptr : "");
3300 	/*
3301 	 * If a PERSISTENT RESERVE OUT command with a REGISTER AND MOVE service
3302 	 * action specifies a TransportID that is the same as the initiator port
3303 	 * of the I_T nexus for the command received, then the command shall
3304 	 * be terminated with CHECK CONDITION status, with the sense key set to
3305 	 * ILLEGAL REQUEST, and the additional sense code set to INVALID FIELD
3306 	 * IN PARAMETER LIST.
3307 	 */
3308 	pr_reg_nacl = pr_reg->pr_reg_nacl;
3309 	matching_iname = (!strcmp(initiator_str,
3310 				  pr_reg_nacl->initiatorname)) ? 1 : 0;
3311 	if (!matching_iname)
3312 		goto after_iport_check;
3313 
3314 	if (!iport_ptr || !pr_reg->isid_present_at_reg) {
3315 		pr_err("SPC-3 PR REGISTER_AND_MOVE: TransportID: %s"
3316 			" matches: %s on received I_T Nexus\n", initiator_str,
3317 			pr_reg_nacl->initiatorname);
3318 		ret = TCM_INVALID_PARAMETER_LIST;
3319 		goto out;
3320 	}
3321 	if (!strcmp(iport_ptr, pr_reg->pr_reg_isid)) {
3322 		pr_err("SPC-3 PR REGISTER_AND_MOVE: TransportID: %s %s"
3323 			" matches: %s %s on received I_T Nexus\n",
3324 			initiator_str, iport_ptr, pr_reg_nacl->initiatorname,
3325 			pr_reg->pr_reg_isid);
3326 		ret = TCM_INVALID_PARAMETER_LIST;
3327 		goto out;
3328 	}
3329 after_iport_check:
3330 	/*
3331 	 * Locate the destination struct se_node_acl from the received Transport ID
3332 	 */
3333 	mutex_lock(&dest_se_tpg->acl_node_mutex);
3334 	dest_node_acl = __core_tpg_get_initiator_node_acl(dest_se_tpg,
3335 				initiator_str);
3336 	if (dest_node_acl)
3337 		atomic_inc_mb(&dest_node_acl->acl_pr_ref_count);
3338 	mutex_unlock(&dest_se_tpg->acl_node_mutex);
3339 
3340 	if (!dest_node_acl) {
3341 		pr_err("Unable to locate %s dest_node_acl for"
3342 			" TransportID%s\n", dest_tf_ops->fabric_name,
3343 			initiator_str);
3344 		ret = TCM_INVALID_PARAMETER_LIST;
3345 		goto out;
3346 	}
3347 
3348 	if (core_scsi3_nodeacl_depend_item(dest_node_acl)) {
3349 		pr_err("core_scsi3_nodeacl_depend_item() for"
3350 			" dest_node_acl\n");
3351 		atomic_dec_mb(&dest_node_acl->acl_pr_ref_count);
3352 		dest_node_acl = NULL;
3353 		ret = TCM_INVALID_PARAMETER_LIST;
3354 		goto out;
3355 	}
3356 
3357 	pr_debug("SPC-3 PR REGISTER_AND_MOVE: Found %s dest_node_acl:"
3358 		" %s from TransportID\n", dest_tf_ops->fabric_name,
3359 		dest_node_acl->initiatorname);
3360 
3361 	/*
3362 	 * Locate the struct se_dev_entry pointer for the matching RELATIVE TARGET
3363 	 * PORT IDENTIFIER.
3364 	 */
3365 	dest_se_deve = core_get_se_deve_from_rtpi(dest_node_acl, rtpi);
3366 	if (!dest_se_deve) {
3367 		pr_err("Unable to locate %s dest_se_deve from RTPI:"
3368 			" %hu\n",  dest_tf_ops->fabric_name, rtpi);
3369 		ret = TCM_INVALID_PARAMETER_LIST;
3370 		goto out;
3371 	}
3372 
3373 	if (core_scsi3_lunacl_depend_item(dest_se_deve)) {
3374 		pr_err("core_scsi3_lunacl_depend_item() failed\n");
3375 		kref_put(&dest_se_deve->pr_kref, target_pr_kref_release);
3376 		dest_se_deve = NULL;
3377 		ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3378 		goto out;
3379 	}
3380 
3381 	pr_debug("SPC-3 PR REGISTER_AND_MOVE: Located %s node %s LUN"
3382 		" ACL for dest_se_deve->mapped_lun: %llu\n",
3383 		dest_tf_ops->fabric_name, dest_node_acl->initiatorname,
3384 		dest_se_deve->mapped_lun);
3385 
3386 	/*
3387 	 * A persistent reservation needs to already existing in order to
3388 	 * successfully complete the REGISTER_AND_MOVE service action..
3389 	 */
3390 	spin_lock(&dev->dev_reservation_lock);
3391 	pr_res_holder = dev->dev_pr_res_holder;
3392 	if (!pr_res_holder) {
3393 		pr_warn("SPC-3 PR REGISTER_AND_MOVE: No reservation"
3394 			" currently held\n");
3395 		spin_unlock(&dev->dev_reservation_lock);
3396 		ret = TCM_INVALID_CDB_FIELD;
3397 		goto out;
3398 	}
3399 	/*
3400 	 * The received on I_T Nexus must be the reservation holder.
3401 	 *
3402 	 * From spc4r17 section 5.7.8  Table 50 --
3403 	 * 	Register behaviors for a REGISTER AND MOVE service action
3404 	 */
3405 	if (!is_reservation_holder(pr_res_holder, pr_reg)) {
3406 		pr_warn("SPC-3 PR REGISTER_AND_MOVE: Calling I_T"
3407 			" Nexus is not reservation holder\n");
3408 		spin_unlock(&dev->dev_reservation_lock);
3409 		ret = TCM_RESERVATION_CONFLICT;
3410 		goto out;
3411 	}
3412 	/*
3413 	 * From spc4r17 section 5.7.8: registering and moving reservation
3414 	 *
3415 	 * If a PERSISTENT RESERVE OUT command with a REGISTER AND MOVE service
3416 	 * action is received and the established persistent reservation is a
3417 	 * Write Exclusive - All Registrants type or Exclusive Access -
3418 	 * All Registrants type reservation, then the command shall be completed
3419 	 * with RESERVATION CONFLICT status.
3420 	 */
3421 	if ((pr_res_holder->pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG) ||
3422 	    (pr_res_holder->pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG)) {
3423 		pr_warn("SPC-3 PR REGISTER_AND_MOVE: Unable to move"
3424 			" reservation for type: %s\n",
3425 			core_scsi3_pr_dump_type(pr_res_holder->pr_res_type));
3426 		spin_unlock(&dev->dev_reservation_lock);
3427 		ret = TCM_RESERVATION_CONFLICT;
3428 		goto out;
3429 	}
3430 	pr_res_nacl = pr_res_holder->pr_reg_nacl;
3431 	/*
3432 	 * b) Ignore the contents of the (received) SCOPE and TYPE fields;
3433 	 */
3434 	type = pr_res_holder->pr_res_type;
3435 	scope = pr_res_holder->pr_res_type;
3436 	/*
3437 	 * c) Associate the reservation key specified in the SERVICE ACTION
3438 	 *    RESERVATION KEY field with the I_T nexus specified as the
3439 	 *    destination of the register and move, where:
3440 	 *    A) The I_T nexus is specified by the TransportID and the
3441 	 *	 RELATIVE TARGET PORT IDENTIFIER field (see 6.14.4); and
3442 	 *    B) Regardless of the TransportID format used, the association for
3443 	 *       the initiator port is based on either the initiator port name
3444 	 *       (see 3.1.71) on SCSI transport protocols where port names are
3445 	 *       required or the initiator port identifier (see 3.1.70) on SCSI
3446 	 *       transport protocols where port names are not required;
3447 	 * d) Register the reservation key specified in the SERVICE ACTION
3448 	 *    RESERVATION KEY field;
3449 	 * e) Retain the reservation key specified in the SERVICE ACTION
3450 	 *    RESERVATION KEY field and associated information;
3451 	 *
3452 	 * Also, It is not an error for a REGISTER AND MOVE service action to
3453 	 * register an I_T nexus that is already registered with the same
3454 	 * reservation key or a different reservation key.
3455 	 */
3456 	dest_pr_reg = __core_scsi3_locate_pr_reg(dev, dest_node_acl,
3457 					iport_ptr);
3458 	if (!dest_pr_reg) {
3459 		struct se_lun *dest_lun = rcu_dereference_check(dest_se_deve->se_lun,
3460 				kref_read(&dest_se_deve->pr_kref) != 0);
3461 
3462 		spin_unlock(&dev->dev_reservation_lock);
3463 		if (core_scsi3_alloc_registration(cmd->se_dev, dest_node_acl,
3464 					dest_lun, dest_se_deve, dest_se_deve->mapped_lun,
3465 					iport_ptr, sa_res_key, 0, aptpl, 2, 1)) {
3466 			ret = TCM_INSUFFICIENT_REGISTRATION_RESOURCES;
3467 			goto out;
3468 		}
3469 		spin_lock(&dev->dev_reservation_lock);
3470 		dest_pr_reg = __core_scsi3_locate_pr_reg(dev, dest_node_acl,
3471 						iport_ptr);
3472 		new_reg = 1;
3473 	}
3474 	/*
3475 	 * f) Release the persistent reservation for the persistent reservation
3476 	 *    holder (i.e., the I_T nexus on which the
3477 	 */
3478 	__core_scsi3_complete_pro_release(dev, pr_res_nacl,
3479 					  dev->dev_pr_res_holder, 0, 0);
3480 	/*
3481 	 * g) Move the persistent reservation to the specified I_T nexus using
3482 	 *    the same scope and type as the persistent reservation released in
3483 	 *    item f); and
3484 	 */
3485 	dev->dev_pr_res_holder = dest_pr_reg;
3486 	dest_pr_reg->pr_res_holder = 1;
3487 	dest_pr_reg->pr_res_type = type;
3488 	pr_reg->pr_res_scope = scope;
3489 	core_pr_dump_initiator_port(pr_reg, i_buf, PR_REG_ISID_ID_LEN);
3490 	/*
3491 	 * Increment PRGeneration for existing registrations..
3492 	 */
3493 	if (!new_reg)
3494 		dest_pr_reg->pr_res_generation = pr_tmpl->pr_generation++;
3495 	spin_unlock(&dev->dev_reservation_lock);
3496 
3497 	pr_debug("SPC-3 PR [%s] Service Action: REGISTER_AND_MOVE"
3498 		" created new reservation holder TYPE: %s on object RTPI:"
3499 		" %hu  PRGeneration: 0x%08x\n", dest_tf_ops->fabric_name,
3500 		core_scsi3_pr_dump_type(type), rtpi,
3501 		dest_pr_reg->pr_res_generation);
3502 	pr_debug("SPC-3 PR Successfully moved reservation from"
3503 		" %s Fabric Node: %s%s -> %s Fabric Node: %s %s\n",
3504 		tf_ops->fabric_name, pr_reg_nacl->initiatorname,
3505 		i_buf, dest_tf_ops->fabric_name,
3506 		dest_node_acl->initiatorname, (iport_ptr != NULL) ?
3507 		iport_ptr : "");
3508 	/*
3509 	 * It is now safe to release configfs group dependencies for destination
3510 	 * of Transport ID Initiator Device/Port Identifier
3511 	 */
3512 	core_scsi3_lunacl_undepend_item(dest_se_deve);
3513 	core_scsi3_nodeacl_undepend_item(dest_node_acl);
3514 	core_scsi3_tpg_undepend_item(dest_se_tpg);
3515 	/*
3516 	 * h) If the UNREG bit is set to one, unregister (see 5.7.11.3) the I_T
3517 	 * nexus on which PERSISTENT RESERVE OUT command was received.
3518 	 */
3519 	if (unreg) {
3520 		spin_lock(&pr_tmpl->registration_lock);
3521 		__core_scsi3_free_registration(dev, pr_reg, NULL, 1);
3522 		spin_unlock(&pr_tmpl->registration_lock);
3523 	} else
3524 		core_scsi3_put_pr_reg(pr_reg);
3525 
3526 	core_scsi3_update_and_write_aptpl(cmd->se_dev, aptpl);
3527 
3528 	core_scsi3_put_pr_reg(dest_pr_reg);
3529 	return 0;
3530 out:
3531 	if (buf)
3532 		transport_kunmap_data_sg(cmd);
3533 	if (dest_se_deve)
3534 		core_scsi3_lunacl_undepend_item(dest_se_deve);
3535 	if (dest_node_acl)
3536 		core_scsi3_nodeacl_undepend_item(dest_node_acl);
3537 	core_scsi3_tpg_undepend_item(dest_se_tpg);
3538 
3539 out_put_pr_reg:
3540 	core_scsi3_put_pr_reg(pr_reg);
3541 	return ret;
3542 }
3543 
3544 /*
3545  * See spc4r17 section 6.14 Table 170
3546  */
3547 sense_reason_t
3548 target_scsi3_emulate_pr_out(struct se_cmd *cmd)
3549 {
3550 	struct se_device *dev = cmd->se_dev;
3551 	unsigned char *cdb = &cmd->t_task_cdb[0];
3552 	unsigned char *buf;
3553 	u64 res_key, sa_res_key;
3554 	int sa, scope, type, aptpl;
3555 	int spec_i_pt = 0, all_tg_pt = 0, unreg = 0;
3556 	sense_reason_t ret;
3557 
3558 	/*
3559 	 * Following spc2r20 5.5.1 Reservations overview:
3560 	 *
3561 	 * If a logical unit has been reserved by any RESERVE command and is
3562 	 * still reserved by any initiator, all PERSISTENT RESERVE IN and all
3563 	 * PERSISTENT RESERVE OUT commands shall conflict regardless of
3564 	 * initiator or service action and shall terminate with a RESERVATION
3565 	 * CONFLICT status.
3566 	 */
3567 	if (cmd->se_dev->dev_reservation_flags & DRF_SPC2_RESERVATIONS) {
3568 		pr_err("Received PERSISTENT_RESERVE CDB while legacy"
3569 			" SPC-2 reservation is held, returning"
3570 			" RESERVATION_CONFLICT\n");
3571 		return TCM_RESERVATION_CONFLICT;
3572 	}
3573 
3574 	/*
3575 	 * FIXME: A NULL struct se_session pointer means an this is not coming from
3576 	 * a $FABRIC_MOD's nexus, but from internal passthrough ops.
3577 	 */
3578 	if (!cmd->se_sess)
3579 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3580 
3581 	if (cmd->data_length < 24) {
3582 		pr_warn("SPC-PR: Received PR OUT parameter list"
3583 			" length too small: %u\n", cmd->data_length);
3584 		return TCM_PARAMETER_LIST_LENGTH_ERROR;
3585 	}
3586 
3587 	/*
3588 	 * From the PERSISTENT_RESERVE_OUT command descriptor block (CDB)
3589 	 */
3590 	sa = (cdb[1] & 0x1f);
3591 	scope = (cdb[2] & 0xf0);
3592 	type = (cdb[2] & 0x0f);
3593 
3594 	buf = transport_kmap_data_sg(cmd);
3595 	if (!buf)
3596 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3597 
3598 	/*
3599 	 * From PERSISTENT_RESERVE_OUT parameter list (payload)
3600 	 */
3601 	res_key = get_unaligned_be64(&buf[0]);
3602 	sa_res_key = get_unaligned_be64(&buf[8]);
3603 	/*
3604 	 * REGISTER_AND_MOVE uses a different SA parameter list containing
3605 	 * SCSI TransportIDs.
3606 	 */
3607 	if (sa != PRO_REGISTER_AND_MOVE) {
3608 		spec_i_pt = (buf[20] & 0x08);
3609 		all_tg_pt = (buf[20] & 0x04);
3610 		aptpl = (buf[20] & 0x01);
3611 	} else {
3612 		aptpl = (buf[17] & 0x01);
3613 		unreg = (buf[17] & 0x02);
3614 	}
3615 	/*
3616 	 * If the backend device has been configured to force APTPL metadata
3617 	 * write-out, go ahead and propigate aptpl=1 down now.
3618 	 */
3619 	if (dev->dev_attrib.force_pr_aptpl)
3620 		aptpl = 1;
3621 
3622 	transport_kunmap_data_sg(cmd);
3623 	buf = NULL;
3624 
3625 	/*
3626 	 * SPEC_I_PT=1 is only valid for Service action: REGISTER
3627 	 */
3628 	if (spec_i_pt && (sa != PRO_REGISTER))
3629 		return TCM_INVALID_PARAMETER_LIST;
3630 
3631 	/*
3632 	 * From spc4r17 section 6.14:
3633 	 *
3634 	 * If the SPEC_I_PT bit is set to zero, the service action is not
3635 	 * REGISTER AND MOVE, and the parameter list length is not 24, then
3636 	 * the command shall be terminated with CHECK CONDITION status, with
3637 	 * the sense key set to ILLEGAL REQUEST, and the additional sense
3638 	 * code set to PARAMETER LIST LENGTH ERROR.
3639 	 */
3640 	if (!spec_i_pt && (sa != PRO_REGISTER_AND_MOVE) &&
3641 	    (cmd->data_length != 24)) {
3642 		pr_warn("SPC-PR: Received PR OUT illegal parameter"
3643 			" list length: %u\n", cmd->data_length);
3644 		return TCM_PARAMETER_LIST_LENGTH_ERROR;
3645 	}
3646 
3647 	/*
3648 	 * (core_scsi3_emulate_pro_* function parameters
3649 	 * are defined by spc4r17 Table 174:
3650 	 * PERSISTENT_RESERVE_OUT service actions and valid parameters.
3651 	 */
3652 	switch (sa) {
3653 	case PRO_REGISTER:
3654 		ret = core_scsi3_emulate_pro_register(cmd,
3655 			res_key, sa_res_key, aptpl, all_tg_pt, spec_i_pt, REGISTER);
3656 		break;
3657 	case PRO_RESERVE:
3658 		ret = core_scsi3_emulate_pro_reserve(cmd, type, scope, res_key);
3659 		break;
3660 	case PRO_RELEASE:
3661 		ret = core_scsi3_emulate_pro_release(cmd, type, scope, res_key);
3662 		break;
3663 	case PRO_CLEAR:
3664 		ret = core_scsi3_emulate_pro_clear(cmd, res_key);
3665 		break;
3666 	case PRO_PREEMPT:
3667 		ret = core_scsi3_emulate_pro_preempt(cmd, type, scope,
3668 					res_key, sa_res_key, PREEMPT);
3669 		break;
3670 	case PRO_PREEMPT_AND_ABORT:
3671 		ret = core_scsi3_emulate_pro_preempt(cmd, type, scope,
3672 					res_key, sa_res_key, PREEMPT_AND_ABORT);
3673 		break;
3674 	case PRO_REGISTER_AND_IGNORE_EXISTING_KEY:
3675 		ret = core_scsi3_emulate_pro_register(cmd,
3676 			0, sa_res_key, aptpl, all_tg_pt, spec_i_pt, REGISTER_AND_IGNORE_EXISTING_KEY);
3677 		break;
3678 	case PRO_REGISTER_AND_MOVE:
3679 		ret = core_scsi3_emulate_pro_register_and_move(cmd, res_key,
3680 				sa_res_key, aptpl, unreg);
3681 		break;
3682 	default:
3683 		pr_err("Unknown PERSISTENT_RESERVE_OUT service"
3684 			" action: 0x%02x\n", sa);
3685 		return TCM_INVALID_CDB_FIELD;
3686 	}
3687 
3688 	if (!ret)
3689 		target_complete_cmd(cmd, GOOD);
3690 	return ret;
3691 }
3692 
3693 /*
3694  * PERSISTENT_RESERVE_IN Service Action READ_KEYS
3695  *
3696  * See spc4r17 section 5.7.6.2 and section 6.13.2, Table 160
3697  */
3698 static sense_reason_t
3699 core_scsi3_pri_read_keys(struct se_cmd *cmd)
3700 {
3701 	struct se_device *dev = cmd->se_dev;
3702 	struct t10_pr_registration *pr_reg;
3703 	unsigned char *buf;
3704 	u32 add_len = 0, off = 8;
3705 
3706 	if (cmd->data_length < 8) {
3707 		pr_err("PRIN SA READ_KEYS SCSI Data Length: %u"
3708 			" too small\n", cmd->data_length);
3709 		return TCM_INVALID_CDB_FIELD;
3710 	}
3711 
3712 	buf = transport_kmap_data_sg(cmd);
3713 	if (!buf)
3714 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3715 
3716 	put_unaligned_be32(dev->t10_pr.pr_generation, buf);
3717 
3718 	spin_lock(&dev->t10_pr.registration_lock);
3719 	list_for_each_entry(pr_reg, &dev->t10_pr.registration_list,
3720 			pr_reg_list) {
3721 		/*
3722 		 * Check for overflow of 8byte PRI READ_KEYS payload and
3723 		 * next reservation key list descriptor.
3724 		 */
3725 		if (off + 8 <= cmd->data_length) {
3726 			put_unaligned_be64(pr_reg->pr_res_key, &buf[off]);
3727 			off += 8;
3728 		}
3729 		/*
3730 		 * SPC5r17: 6.16.2 READ KEYS service action
3731 		 * The ADDITIONAL LENGTH field indicates the number of bytes in
3732 		 * the Reservation key list. The contents of the ADDITIONAL
3733 		 * LENGTH field are not altered based on the allocation length
3734 		 */
3735 		add_len += 8;
3736 	}
3737 	spin_unlock(&dev->t10_pr.registration_lock);
3738 
3739 	put_unaligned_be32(add_len, &buf[4]);
3740 
3741 	transport_kunmap_data_sg(cmd);
3742 
3743 	return 0;
3744 }
3745 
3746 /*
3747  * PERSISTENT_RESERVE_IN Service Action READ_RESERVATION
3748  *
3749  * See spc4r17 section 5.7.6.3 and section 6.13.3.2 Table 161 and 162
3750  */
3751 static sense_reason_t
3752 core_scsi3_pri_read_reservation(struct se_cmd *cmd)
3753 {
3754 	struct se_device *dev = cmd->se_dev;
3755 	struct t10_pr_registration *pr_reg;
3756 	unsigned char *buf;
3757 	u64 pr_res_key;
3758 	u32 add_len = 16; /* Hardcoded to 16 when a reservation is held. */
3759 
3760 	if (cmd->data_length < 8) {
3761 		pr_err("PRIN SA READ_RESERVATIONS SCSI Data Length: %u"
3762 			" too small\n", cmd->data_length);
3763 		return TCM_INVALID_CDB_FIELD;
3764 	}
3765 
3766 	buf = transport_kmap_data_sg(cmd);
3767 	if (!buf)
3768 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3769 
3770 	put_unaligned_be32(dev->t10_pr.pr_generation, &buf[0]);
3771 
3772 	spin_lock(&dev->dev_reservation_lock);
3773 	pr_reg = dev->dev_pr_res_holder;
3774 	if (pr_reg) {
3775 		/*
3776 		 * Set the hardcoded Additional Length
3777 		 */
3778 		put_unaligned_be32(add_len, &buf[4]);
3779 
3780 		if (cmd->data_length < 22)
3781 			goto err;
3782 
3783 		/*
3784 		 * Set the Reservation key.
3785 		 *
3786 		 * From spc4r17, section 5.7.10:
3787 		 * A persistent reservation holder has its reservation key
3788 		 * returned in the parameter data from a PERSISTENT
3789 		 * RESERVE IN command with READ RESERVATION service action as
3790 		 * follows:
3791 		 * a) For a persistent reservation of the type Write Exclusive
3792 		 *    - All Registrants or Exclusive Access ­ All Regitrants,
3793 		 *      the reservation key shall be set to zero; or
3794 		 * b) For all other persistent reservation types, the
3795 		 *    reservation key shall be set to the registered
3796 		 *    reservation key for the I_T nexus that holds the
3797 		 *    persistent reservation.
3798 		 */
3799 		if ((pr_reg->pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG) ||
3800 		    (pr_reg->pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG))
3801 			pr_res_key = 0;
3802 		else
3803 			pr_res_key = pr_reg->pr_res_key;
3804 
3805 		put_unaligned_be64(pr_res_key, &buf[8]);
3806 		/*
3807 		 * Set the SCOPE and TYPE
3808 		 */
3809 		buf[21] = (pr_reg->pr_res_scope & 0xf0) |
3810 			  (pr_reg->pr_res_type & 0x0f);
3811 	}
3812 
3813 err:
3814 	spin_unlock(&dev->dev_reservation_lock);
3815 	transport_kunmap_data_sg(cmd);
3816 
3817 	return 0;
3818 }
3819 
3820 /*
3821  * PERSISTENT_RESERVE_IN Service Action REPORT_CAPABILITIES
3822  *
3823  * See spc4r17 section 6.13.4 Table 165
3824  */
3825 static sense_reason_t
3826 core_scsi3_pri_report_capabilities(struct se_cmd *cmd)
3827 {
3828 	struct se_device *dev = cmd->se_dev;
3829 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
3830 	unsigned char *buf;
3831 	u16 add_len = 8; /* Hardcoded to 8. */
3832 
3833 	if (cmd->data_length < 6) {
3834 		pr_err("PRIN SA REPORT_CAPABILITIES SCSI Data Length:"
3835 			" %u too small\n", cmd->data_length);
3836 		return TCM_INVALID_CDB_FIELD;
3837 	}
3838 
3839 	buf = transport_kmap_data_sg(cmd);
3840 	if (!buf)
3841 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3842 
3843 	put_unaligned_be16(add_len, &buf[0]);
3844 	buf[2] |= 0x10; /* CRH: Compatible Reservation Hanlding bit. */
3845 	buf[2] |= 0x08; /* SIP_C: Specify Initiator Ports Capable bit */
3846 	buf[2] |= 0x04; /* ATP_C: All Target Ports Capable bit */
3847 	buf[2] |= 0x01; /* PTPL_C: Persistence across Target Power Loss bit */
3848 	/*
3849 	 * We are filling in the PERSISTENT RESERVATION TYPE MASK below, so
3850 	 * set the TMV: Task Mask Valid bit.
3851 	 */
3852 	buf[3] |= 0x80;
3853 	/*
3854 	 * Change ALLOW COMMANDs to 0x20 or 0x40 later from Table 166
3855 	 */
3856 	buf[3] |= 0x10; /* ALLOW COMMANDs field 001b */
3857 	/*
3858 	 * PTPL_A: Persistence across Target Power Loss Active bit
3859 	 */
3860 	if (pr_tmpl->pr_aptpl_active)
3861 		buf[3] |= 0x01;
3862 	/*
3863 	 * Setup the PERSISTENT RESERVATION TYPE MASK from Table 167
3864 	 */
3865 	buf[4] |= 0x80; /* PR_TYPE_EXCLUSIVE_ACCESS_ALLREG */
3866 	buf[4] |= 0x40; /* PR_TYPE_EXCLUSIVE_ACCESS_REGONLY */
3867 	buf[4] |= 0x20; /* PR_TYPE_WRITE_EXCLUSIVE_REGONLY */
3868 	buf[4] |= 0x08; /* PR_TYPE_EXCLUSIVE_ACCESS */
3869 	buf[4] |= 0x02; /* PR_TYPE_WRITE_EXCLUSIVE */
3870 	buf[5] |= 0x01; /* PR_TYPE_EXCLUSIVE_ACCESS_ALLREG */
3871 
3872 	transport_kunmap_data_sg(cmd);
3873 
3874 	return 0;
3875 }
3876 
3877 /*
3878  * PERSISTENT_RESERVE_IN Service Action READ_FULL_STATUS
3879  *
3880  * See spc4r17 section 6.13.5 Table 168 and 169
3881  */
3882 static sense_reason_t
3883 core_scsi3_pri_read_full_status(struct se_cmd *cmd)
3884 {
3885 	struct se_device *dev = cmd->se_dev;
3886 	struct se_node_acl *se_nacl;
3887 	struct se_portal_group *se_tpg;
3888 	struct t10_pr_registration *pr_reg, *pr_reg_tmp;
3889 	struct t10_reservation *pr_tmpl = &dev->t10_pr;
3890 	unsigned char *buf;
3891 	u32 add_desc_len = 0, add_len = 0;
3892 	u32 off = 8; /* off into first Full Status descriptor */
3893 	int format_code = 0, pr_res_type = 0, pr_res_scope = 0;
3894 	int exp_desc_len, desc_len;
3895 	bool all_reg = false;
3896 
3897 	if (cmd->data_length < 8) {
3898 		pr_err("PRIN SA READ_FULL_STATUS SCSI Data Length: %u"
3899 			" too small\n", cmd->data_length);
3900 		return TCM_INVALID_CDB_FIELD;
3901 	}
3902 
3903 	buf = transport_kmap_data_sg(cmd);
3904 	if (!buf)
3905 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3906 
3907 	put_unaligned_be32(dev->t10_pr.pr_generation, &buf[0]);
3908 
3909 	spin_lock(&dev->dev_reservation_lock);
3910 	if (dev->dev_pr_res_holder) {
3911 		struct t10_pr_registration *pr_holder = dev->dev_pr_res_holder;
3912 
3913 		if (pr_holder->pr_res_type == PR_TYPE_WRITE_EXCLUSIVE_ALLREG ||
3914 		    pr_holder->pr_res_type == PR_TYPE_EXCLUSIVE_ACCESS_ALLREG) {
3915 			all_reg = true;
3916 			pr_res_type = pr_holder->pr_res_type;
3917 			pr_res_scope = pr_holder->pr_res_scope;
3918 		}
3919 	}
3920 	spin_unlock(&dev->dev_reservation_lock);
3921 
3922 	spin_lock(&pr_tmpl->registration_lock);
3923 	list_for_each_entry_safe(pr_reg, pr_reg_tmp,
3924 			&pr_tmpl->registration_list, pr_reg_list) {
3925 
3926 		se_nacl = pr_reg->pr_reg_nacl;
3927 		se_tpg = pr_reg->pr_reg_nacl->se_tpg;
3928 		add_desc_len = 0;
3929 
3930 		atomic_inc_mb(&pr_reg->pr_res_holders);
3931 		spin_unlock(&pr_tmpl->registration_lock);
3932 		/*
3933 		 * Determine expected length of $FABRIC_MOD specific
3934 		 * TransportID full status descriptor..
3935 		 */
3936 		exp_desc_len = target_get_pr_transport_id_len(se_nacl, pr_reg,
3937 					&format_code);
3938 		if (exp_desc_len < 0 ||
3939 		    exp_desc_len + add_len > cmd->data_length) {
3940 			pr_warn("SPC-3 PRIN READ_FULL_STATUS ran"
3941 				" out of buffer: %d\n", cmd->data_length);
3942 			spin_lock(&pr_tmpl->registration_lock);
3943 			atomic_dec_mb(&pr_reg->pr_res_holders);
3944 			break;
3945 		}
3946 		/*
3947 		 * Set RESERVATION KEY
3948 		 */
3949 		put_unaligned_be64(pr_reg->pr_res_key, &buf[off]);
3950 		off += 8;
3951 		off += 4; /* Skip Over Reserved area */
3952 
3953 		/*
3954 		 * Set ALL_TG_PT bit if PROUT SA REGISTER had this set.
3955 		 */
3956 		if (pr_reg->pr_reg_all_tg_pt)
3957 			buf[off] = 0x02;
3958 		/*
3959 		 * The struct se_lun pointer will be present for the
3960 		 * reservation holder for PR_HOLDER bit.
3961 		 *
3962 		 * Also, if this registration is the reservation
3963 		 * holder or there is an All Registrants reservation
3964 		 * active, fill in SCOPE and TYPE in the next byte.
3965 		 */
3966 		if (pr_reg->pr_res_holder) {
3967 			buf[off++] |= 0x01;
3968 			buf[off++] = (pr_reg->pr_res_scope & 0xf0) |
3969 				     (pr_reg->pr_res_type & 0x0f);
3970 		} else if (all_reg) {
3971 			buf[off++] |= 0x01;
3972 			buf[off++] = (pr_res_scope & 0xf0) |
3973 				     (pr_res_type & 0x0f);
3974 		} else {
3975 			off += 2;
3976 		}
3977 
3978 		off += 4; /* Skip over reserved area */
3979 		/*
3980 		 * From spc4r17 6.3.15:
3981 		 *
3982 		 * If the ALL_TG_PT bit set to zero, the RELATIVE TARGET PORT
3983 		 * IDENTIFIER field contains the relative port identifier (see
3984 		 * 3.1.120) of the target port that is part of the I_T nexus
3985 		 * described by this full status descriptor. If the ALL_TG_PT
3986 		 * bit is set to one, the contents of the RELATIVE TARGET PORT
3987 		 * IDENTIFIER field are not defined by this standard.
3988 		 */
3989 		if (!pr_reg->pr_reg_all_tg_pt) {
3990 			u16 sep_rtpi = pr_reg->tg_pt_sep_rtpi;
3991 
3992 			put_unaligned_be16(sep_rtpi, &buf[off]);
3993 			off += 2;
3994 		} else
3995 			off += 2; /* Skip over RELATIVE TARGET PORT IDENTIFIER */
3996 
3997 		buf[off+4] = se_tpg->proto_id;
3998 
3999 		/*
4000 		 * Now, have the $FABRIC_MOD fill in the transport ID.
4001 		 */
4002 		desc_len = target_get_pr_transport_id(se_nacl, pr_reg,
4003 				&format_code, &buf[off+4]);
4004 
4005 		spin_lock(&pr_tmpl->registration_lock);
4006 		atomic_dec_mb(&pr_reg->pr_res_holders);
4007 
4008 		if (desc_len < 0)
4009 			break;
4010 		/*
4011 		 * Set the ADDITIONAL DESCRIPTOR LENGTH
4012 		 */
4013 		put_unaligned_be32(desc_len, &buf[off]);
4014 		off += 4;
4015 		/*
4016 		 * Size of full desctipor header minus TransportID
4017 		 * containing $FABRIC_MOD specific) initiator device/port
4018 		 * WWN information.
4019 		 *
4020 		 *  See spc4r17 Section 6.13.5 Table 169
4021 		 */
4022 		add_desc_len = (24 + desc_len);
4023 
4024 		off += desc_len;
4025 		add_len += add_desc_len;
4026 	}
4027 	spin_unlock(&pr_tmpl->registration_lock);
4028 	/*
4029 	 * Set ADDITIONAL_LENGTH
4030 	 */
4031 	put_unaligned_be32(add_len, &buf[4]);
4032 
4033 	transport_kunmap_data_sg(cmd);
4034 
4035 	return 0;
4036 }
4037 
4038 sense_reason_t
4039 target_scsi3_emulate_pr_in(struct se_cmd *cmd)
4040 {
4041 	sense_reason_t ret;
4042 
4043 	/*
4044 	 * Following spc2r20 5.5.1 Reservations overview:
4045 	 *
4046 	 * If a logical unit has been reserved by any RESERVE command and is
4047 	 * still reserved by any initiator, all PERSISTENT RESERVE IN and all
4048 	 * PERSISTENT RESERVE OUT commands shall conflict regardless of
4049 	 * initiator or service action and shall terminate with a RESERVATION
4050 	 * CONFLICT status.
4051 	 */
4052 	if (cmd->se_dev->dev_reservation_flags & DRF_SPC2_RESERVATIONS) {
4053 		pr_err("Received PERSISTENT_RESERVE CDB while legacy"
4054 			" SPC-2 reservation is held, returning"
4055 			" RESERVATION_CONFLICT\n");
4056 		return TCM_RESERVATION_CONFLICT;
4057 	}
4058 
4059 	switch (cmd->t_task_cdb[1] & 0x1f) {
4060 	case PRI_READ_KEYS:
4061 		ret = core_scsi3_pri_read_keys(cmd);
4062 		break;
4063 	case PRI_READ_RESERVATION:
4064 		ret = core_scsi3_pri_read_reservation(cmd);
4065 		break;
4066 	case PRI_REPORT_CAPABILITIES:
4067 		ret = core_scsi3_pri_report_capabilities(cmd);
4068 		break;
4069 	case PRI_READ_FULL_STATUS:
4070 		ret = core_scsi3_pri_read_full_status(cmd);
4071 		break;
4072 	default:
4073 		pr_err("Unknown PERSISTENT_RESERVE_IN service"
4074 			" action: 0x%02x\n", cmd->t_task_cdb[1] & 0x1f);
4075 		return TCM_INVALID_CDB_FIELD;
4076 	}
4077 
4078 	if (!ret)
4079 		target_complete_cmd(cmd, GOOD);
4080 	return ret;
4081 }
4082 
4083 sense_reason_t
4084 target_check_reservation(struct se_cmd *cmd)
4085 {
4086 	struct se_device *dev = cmd->se_dev;
4087 	sense_reason_t ret;
4088 
4089 	if (!cmd->se_sess)
4090 		return 0;
4091 	if (dev->se_hba->hba_flags & HBA_FLAGS_INTERNAL_USE)
4092 		return 0;
4093 	if (!dev->dev_attrib.emulate_pr)
4094 		return 0;
4095 	if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH_PGR)
4096 		return 0;
4097 
4098 	spin_lock(&dev->dev_reservation_lock);
4099 	if (dev->dev_reservation_flags & DRF_SPC2_RESERVATIONS)
4100 		ret = target_scsi2_reservation_check(cmd);
4101 	else
4102 		ret = target_scsi3_pr_reservation_check(cmd);
4103 	spin_unlock(&dev->dev_reservation_lock);
4104 
4105 	return ret;
4106 }
4107