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