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