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