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