]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/target/target_core_transport.c
Merge remote-tracking branch 'target-updates/for-next'
[karo-tx-linux.git] / drivers / target / target_core_transport.c
1 /*******************************************************************************
2  * Filename:  target_core_transport.c
3  *
4  * This file contains the Generic Target Engine Core.
5  *
6  * Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
7  * Copyright (c) 2005, 2006, 2007 SBE, Inc.
8  * Copyright (c) 2007-2010 Rising Tide Systems
9  * Copyright (c) 2008-2010 Linux-iSCSI.org
10  *
11  * Nicholas A. Bellinger <nab@kernel.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26  *
27  ******************************************************************************/
28
29 #include <linux/net.h>
30 #include <linux/delay.h>
31 #include <linux/string.h>
32 #include <linux/timer.h>
33 #include <linux/slab.h>
34 #include <linux/blkdev.h>
35 #include <linux/spinlock.h>
36 #include <linux/kthread.h>
37 #include <linux/in.h>
38 #include <linux/cdrom.h>
39 #include <linux/module.h>
40 #include <linux/ratelimit.h>
41 #include <asm/unaligned.h>
42 #include <net/sock.h>
43 #include <net/tcp.h>
44 #include <scsi/scsi.h>
45 #include <scsi/scsi_cmnd.h>
46 #include <scsi/scsi_tcq.h>
47
48 #include <target/target_core_base.h>
49 #include <target/target_core_backend.h>
50 #include <target/target_core_fabric.h>
51 #include <target/target_core_configfs.h>
52
53 #include "target_core_internal.h"
54 #include "target_core_alua.h"
55 #include "target_core_pr.h"
56 #include "target_core_ua.h"
57
58 static struct workqueue_struct *target_completion_wq;
59 static struct kmem_cache *se_sess_cache;
60 struct kmem_cache *se_ua_cache;
61 struct kmem_cache *t10_pr_reg_cache;
62 struct kmem_cache *t10_alua_lu_gp_cache;
63 struct kmem_cache *t10_alua_lu_gp_mem_cache;
64 struct kmem_cache *t10_alua_tg_pt_gp_cache;
65 struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
66
67 static void transport_complete_task_attr(struct se_cmd *cmd);
68 static void transport_handle_queue_full(struct se_cmd *cmd,
69                 struct se_device *dev);
70 static int transport_generic_get_mem(struct se_cmd *cmd);
71 static int target_get_sess_cmd(struct se_session *, struct se_cmd *, bool);
72 static void transport_put_cmd(struct se_cmd *cmd);
73 static int transport_set_sense_codes(struct se_cmd *cmd, u8 asc, u8 ascq);
74 static void target_complete_ok_work(struct work_struct *work);
75
76 int init_se_kmem_caches(void)
77 {
78         se_sess_cache = kmem_cache_create("se_sess_cache",
79                         sizeof(struct se_session), __alignof__(struct se_session),
80                         0, NULL);
81         if (!se_sess_cache) {
82                 pr_err("kmem_cache_create() for struct se_session"
83                                 " failed\n");
84                 goto out;
85         }
86         se_ua_cache = kmem_cache_create("se_ua_cache",
87                         sizeof(struct se_ua), __alignof__(struct se_ua),
88                         0, NULL);
89         if (!se_ua_cache) {
90                 pr_err("kmem_cache_create() for struct se_ua failed\n");
91                 goto out_free_sess_cache;
92         }
93         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
94                         sizeof(struct t10_pr_registration),
95                         __alignof__(struct t10_pr_registration), 0, NULL);
96         if (!t10_pr_reg_cache) {
97                 pr_err("kmem_cache_create() for struct t10_pr_registration"
98                                 " failed\n");
99                 goto out_free_ua_cache;
100         }
101         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
102                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
103                         0, NULL);
104         if (!t10_alua_lu_gp_cache) {
105                 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
106                                 " failed\n");
107                 goto out_free_pr_reg_cache;
108         }
109         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
110                         sizeof(struct t10_alua_lu_gp_member),
111                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
112         if (!t10_alua_lu_gp_mem_cache) {
113                 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
114                                 "cache failed\n");
115                 goto out_free_lu_gp_cache;
116         }
117         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
118                         sizeof(struct t10_alua_tg_pt_gp),
119                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
120         if (!t10_alua_tg_pt_gp_cache) {
121                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
122                                 "cache failed\n");
123                 goto out_free_lu_gp_mem_cache;
124         }
125         t10_alua_tg_pt_gp_mem_cache = kmem_cache_create(
126                         "t10_alua_tg_pt_gp_mem_cache",
127                         sizeof(struct t10_alua_tg_pt_gp_member),
128                         __alignof__(struct t10_alua_tg_pt_gp_member),
129                         0, NULL);
130         if (!t10_alua_tg_pt_gp_mem_cache) {
131                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
132                                 "mem_t failed\n");
133                 goto out_free_tg_pt_gp_cache;
134         }
135
136         target_completion_wq = alloc_workqueue("target_completion",
137                                                WQ_MEM_RECLAIM, 0);
138         if (!target_completion_wq)
139                 goto out_free_tg_pt_gp_mem_cache;
140
141         return 0;
142
143 out_free_tg_pt_gp_mem_cache:
144         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
145 out_free_tg_pt_gp_cache:
146         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
147 out_free_lu_gp_mem_cache:
148         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
149 out_free_lu_gp_cache:
150         kmem_cache_destroy(t10_alua_lu_gp_cache);
151 out_free_pr_reg_cache:
152         kmem_cache_destroy(t10_pr_reg_cache);
153 out_free_ua_cache:
154         kmem_cache_destroy(se_ua_cache);
155 out_free_sess_cache:
156         kmem_cache_destroy(se_sess_cache);
157 out:
158         return -ENOMEM;
159 }
160
161 void release_se_kmem_caches(void)
162 {
163         destroy_workqueue(target_completion_wq);
164         kmem_cache_destroy(se_sess_cache);
165         kmem_cache_destroy(se_ua_cache);
166         kmem_cache_destroy(t10_pr_reg_cache);
167         kmem_cache_destroy(t10_alua_lu_gp_cache);
168         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
169         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
170         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
171 }
172
173 /* This code ensures unique mib indexes are handed out. */
174 static DEFINE_SPINLOCK(scsi_mib_index_lock);
175 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
176
177 /*
178  * Allocate a new row index for the entry type specified
179  */
180 u32 scsi_get_new_index(scsi_index_t type)
181 {
182         u32 new_index;
183
184         BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
185
186         spin_lock(&scsi_mib_index_lock);
187         new_index = ++scsi_mib_index[type];
188         spin_unlock(&scsi_mib_index_lock);
189
190         return new_index;
191 }
192
193 void transport_subsystem_check_init(void)
194 {
195         int ret;
196         static int sub_api_initialized;
197
198         if (sub_api_initialized)
199                 return;
200
201         ret = request_module("target_core_iblock");
202         if (ret != 0)
203                 pr_err("Unable to load target_core_iblock\n");
204
205         ret = request_module("target_core_file");
206         if (ret != 0)
207                 pr_err("Unable to load target_core_file\n");
208
209         ret = request_module("target_core_pscsi");
210         if (ret != 0)
211                 pr_err("Unable to load target_core_pscsi\n");
212
213         sub_api_initialized = 1;
214 }
215
216 struct se_session *transport_init_session(void)
217 {
218         struct se_session *se_sess;
219
220         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
221         if (!se_sess) {
222                 pr_err("Unable to allocate struct se_session from"
223                                 " se_sess_cache\n");
224                 return ERR_PTR(-ENOMEM);
225         }
226         INIT_LIST_HEAD(&se_sess->sess_list);
227         INIT_LIST_HEAD(&se_sess->sess_acl_list);
228         INIT_LIST_HEAD(&se_sess->sess_cmd_list);
229         spin_lock_init(&se_sess->sess_cmd_lock);
230         kref_init(&se_sess->sess_kref);
231
232         return se_sess;
233 }
234 EXPORT_SYMBOL(transport_init_session);
235
236 /*
237  * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
238  */
239 void __transport_register_session(
240         struct se_portal_group *se_tpg,
241         struct se_node_acl *se_nacl,
242         struct se_session *se_sess,
243         void *fabric_sess_ptr)
244 {
245         unsigned char buf[PR_REG_ISID_LEN];
246
247         se_sess->se_tpg = se_tpg;
248         se_sess->fabric_sess_ptr = fabric_sess_ptr;
249         /*
250          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
251          *
252          * Only set for struct se_session's that will actually be moving I/O.
253          * eg: *NOT* discovery sessions.
254          */
255         if (se_nacl) {
256                 /*
257                  * If the fabric module supports an ISID based TransportID,
258                  * save this value in binary from the fabric I_T Nexus now.
259                  */
260                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
261                         memset(&buf[0], 0, PR_REG_ISID_LEN);
262                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
263                                         &buf[0], PR_REG_ISID_LEN);
264                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
265                 }
266                 kref_get(&se_nacl->acl_kref);
267
268                 spin_lock_irq(&se_nacl->nacl_sess_lock);
269                 /*
270                  * The se_nacl->nacl_sess pointer will be set to the
271                  * last active I_T Nexus for each struct se_node_acl.
272                  */
273                 se_nacl->nacl_sess = se_sess;
274
275                 list_add_tail(&se_sess->sess_acl_list,
276                               &se_nacl->acl_sess_list);
277                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
278         }
279         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
280
281         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
282                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
283 }
284 EXPORT_SYMBOL(__transport_register_session);
285
286 void transport_register_session(
287         struct se_portal_group *se_tpg,
288         struct se_node_acl *se_nacl,
289         struct se_session *se_sess,
290         void *fabric_sess_ptr)
291 {
292         unsigned long flags;
293
294         spin_lock_irqsave(&se_tpg->session_lock, flags);
295         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
296         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
297 }
298 EXPORT_SYMBOL(transport_register_session);
299
300 void target_release_session(struct kref *kref)
301 {
302         struct se_session *se_sess = container_of(kref,
303                         struct se_session, sess_kref);
304         struct se_portal_group *se_tpg = se_sess->se_tpg;
305
306         se_tpg->se_tpg_tfo->close_session(se_sess);
307 }
308
309 void target_get_session(struct se_session *se_sess)
310 {
311         kref_get(&se_sess->sess_kref);
312 }
313 EXPORT_SYMBOL(target_get_session);
314
315 void target_put_session(struct se_session *se_sess)
316 {
317         struct se_portal_group *tpg = se_sess->se_tpg;
318
319         if (tpg->se_tpg_tfo->put_session != NULL) {
320                 tpg->se_tpg_tfo->put_session(se_sess);
321                 return;
322         }
323         kref_put(&se_sess->sess_kref, target_release_session);
324 }
325 EXPORT_SYMBOL(target_put_session);
326
327 static void target_complete_nacl(struct kref *kref)
328 {
329         struct se_node_acl *nacl = container_of(kref,
330                                 struct se_node_acl, acl_kref);
331
332         complete(&nacl->acl_free_comp);
333 }
334
335 void target_put_nacl(struct se_node_acl *nacl)
336 {
337         kref_put(&nacl->acl_kref, target_complete_nacl);
338 }
339
340 void transport_deregister_session_configfs(struct se_session *se_sess)
341 {
342         struct se_node_acl *se_nacl;
343         unsigned long flags;
344         /*
345          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
346          */
347         se_nacl = se_sess->se_node_acl;
348         if (se_nacl) {
349                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
350                 if (se_nacl->acl_stop == 0)
351                         list_del(&se_sess->sess_acl_list);
352                 /*
353                  * If the session list is empty, then clear the pointer.
354                  * Otherwise, set the struct se_session pointer from the tail
355                  * element of the per struct se_node_acl active session list.
356                  */
357                 if (list_empty(&se_nacl->acl_sess_list))
358                         se_nacl->nacl_sess = NULL;
359                 else {
360                         se_nacl->nacl_sess = container_of(
361                                         se_nacl->acl_sess_list.prev,
362                                         struct se_session, sess_acl_list);
363                 }
364                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
365         }
366 }
367 EXPORT_SYMBOL(transport_deregister_session_configfs);
368
369 void transport_free_session(struct se_session *se_sess)
370 {
371         kmem_cache_free(se_sess_cache, se_sess);
372 }
373 EXPORT_SYMBOL(transport_free_session);
374
375 void transport_deregister_session(struct se_session *se_sess)
376 {
377         struct se_portal_group *se_tpg = se_sess->se_tpg;
378         struct target_core_fabric_ops *se_tfo;
379         struct se_node_acl *se_nacl;
380         unsigned long flags;
381         bool comp_nacl = true;
382
383         if (!se_tpg) {
384                 transport_free_session(se_sess);
385                 return;
386         }
387         se_tfo = se_tpg->se_tpg_tfo;
388
389         spin_lock_irqsave(&se_tpg->session_lock, flags);
390         list_del(&se_sess->sess_list);
391         se_sess->se_tpg = NULL;
392         se_sess->fabric_sess_ptr = NULL;
393         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
394
395         /*
396          * Determine if we need to do extra work for this initiator node's
397          * struct se_node_acl if it had been previously dynamically generated.
398          */
399         se_nacl = se_sess->se_node_acl;
400
401         spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
402         if (se_nacl && se_nacl->dynamic_node_acl) {
403                 if (!se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
404                         list_del(&se_nacl->acl_list);
405                         se_tpg->num_node_acls--;
406                         spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
407                         core_tpg_wait_for_nacl_pr_ref(se_nacl);
408                         core_free_device_list_for_node(se_nacl, se_tpg);
409                         se_tfo->tpg_release_fabric_acl(se_tpg, se_nacl);
410
411                         comp_nacl = false;
412                         spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
413                 }
414         }
415         spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
416
417         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
418                 se_tpg->se_tpg_tfo->get_fabric_name());
419         /*
420          * If last kref is dropping now for an explict NodeACL, awake sleeping
421          * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
422          * removal context.
423          */
424         if (se_nacl && comp_nacl == true)
425                 target_put_nacl(se_nacl);
426
427         transport_free_session(se_sess);
428 }
429 EXPORT_SYMBOL(transport_deregister_session);
430
431 /*
432  * Called with cmd->t_state_lock held.
433  */
434 static void target_remove_from_state_list(struct se_cmd *cmd)
435 {
436         struct se_device *dev = cmd->se_dev;
437         unsigned long flags;
438
439         if (!dev)
440                 return;
441
442         if (cmd->transport_state & CMD_T_BUSY)
443                 return;
444
445         spin_lock_irqsave(&dev->execute_task_lock, flags);
446         if (cmd->state_active) {
447                 list_del(&cmd->state_list);
448                 cmd->state_active = false;
449         }
450         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
451 }
452
453 static int transport_cmd_check_stop(struct se_cmd *cmd, bool remove_from_lists)
454 {
455         unsigned long flags;
456
457         spin_lock_irqsave(&cmd->t_state_lock, flags);
458         /*
459          * Determine if IOCTL context caller in requesting the stopping of this
460          * command for LUN shutdown purposes.
461          */
462         if (cmd->transport_state & CMD_T_LUN_STOP) {
463                 pr_debug("%s:%d CMD_T_LUN_STOP for ITT: 0x%08x\n",
464                         __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd));
465
466                 cmd->transport_state &= ~CMD_T_ACTIVE;
467                 if (remove_from_lists)
468                         target_remove_from_state_list(cmd);
469                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
470
471                 complete(&cmd->transport_lun_stop_comp);
472                 return 1;
473         }
474
475         if (remove_from_lists) {
476                 target_remove_from_state_list(cmd);
477
478                 /*
479                  * Clear struct se_cmd->se_lun before the handoff to FE.
480                  */
481                 cmd->se_lun = NULL;
482         }
483
484         /*
485          * Determine if frontend context caller is requesting the stopping of
486          * this command for frontend exceptions.
487          */
488         if (cmd->transport_state & CMD_T_STOP) {
489                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n",
490                         __func__, __LINE__,
491                         cmd->se_tfo->get_task_tag(cmd));
492
493                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
494
495                 complete(&cmd->t_transport_stop_comp);
496                 return 1;
497         }
498
499         cmd->transport_state &= ~CMD_T_ACTIVE;
500         if (remove_from_lists) {
501                 /*
502                  * Some fabric modules like tcm_loop can release
503                  * their internally allocated I/O reference now and
504                  * struct se_cmd now.
505                  *
506                  * Fabric modules are expected to return '1' here if the
507                  * se_cmd being passed is released at this point,
508                  * or zero if not being released.
509                  */
510                 if (cmd->se_tfo->check_stop_free != NULL) {
511                         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
512                         return cmd->se_tfo->check_stop_free(cmd);
513                 }
514         }
515
516         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
517         return 0;
518 }
519
520 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
521 {
522         return transport_cmd_check_stop(cmd, true);
523 }
524
525 static void transport_lun_remove_cmd(struct se_cmd *cmd)
526 {
527         struct se_lun *lun = cmd->se_lun;
528         unsigned long flags;
529
530         if (!lun)
531                 return;
532
533         spin_lock_irqsave(&cmd->t_state_lock, flags);
534         if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
535                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
536                 target_remove_from_state_list(cmd);
537         }
538         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
539
540         spin_lock_irqsave(&lun->lun_cmd_lock, flags);
541         if (!list_empty(&cmd->se_lun_node))
542                 list_del_init(&cmd->se_lun_node);
543         spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
544 }
545
546 void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
547 {
548         if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
549                 transport_lun_remove_cmd(cmd);
550
551         if (transport_cmd_check_stop_to_fabric(cmd))
552                 return;
553         if (remove)
554                 transport_put_cmd(cmd);
555 }
556
557 static void target_complete_failure_work(struct work_struct *work)
558 {
559         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
560
561         transport_generic_request_failure(cmd);
562 }
563
564 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
565 {
566         struct se_device *dev = cmd->se_dev;
567         int success = scsi_status == GOOD;
568         unsigned long flags;
569
570         cmd->scsi_status = scsi_status;
571
572
573         spin_lock_irqsave(&cmd->t_state_lock, flags);
574         cmd->transport_state &= ~CMD_T_BUSY;
575
576         if (dev && dev->transport->transport_complete) {
577                 if (dev->transport->transport_complete(cmd,
578                                 cmd->t_data_sg) != 0) {
579                         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
580                         success = 1;
581                 }
582         }
583
584         /*
585          * See if we are waiting to complete for an exception condition.
586          */
587         if (cmd->transport_state & CMD_T_REQUEST_STOP) {
588                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
589                 complete(&cmd->task_stop_comp);
590                 return;
591         }
592
593         if (!success)
594                 cmd->transport_state |= CMD_T_FAILED;
595
596         /*
597          * Check for case where an explict ABORT_TASK has been received
598          * and transport_wait_for_tasks() will be waiting for completion..
599          */
600         if (cmd->transport_state & CMD_T_ABORTED &&
601             cmd->transport_state & CMD_T_STOP) {
602                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
603                 complete(&cmd->t_transport_stop_comp);
604                 return;
605         } else if (cmd->transport_state & CMD_T_FAILED) {
606                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
607                 INIT_WORK(&cmd->work, target_complete_failure_work);
608         } else {
609                 INIT_WORK(&cmd->work, target_complete_ok_work);
610         }
611
612         cmd->t_state = TRANSPORT_COMPLETE;
613         cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
614         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
615
616         queue_work(target_completion_wq, &cmd->work);
617 }
618 EXPORT_SYMBOL(target_complete_cmd);
619
620 static void target_add_to_state_list(struct se_cmd *cmd)
621 {
622         struct se_device *dev = cmd->se_dev;
623         unsigned long flags;
624
625         spin_lock_irqsave(&dev->execute_task_lock, flags);
626         if (!cmd->state_active) {
627                 list_add_tail(&cmd->state_list, &dev->state_list);
628                 cmd->state_active = true;
629         }
630         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
631 }
632
633 /*
634  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
635  */
636 static void transport_write_pending_qf(struct se_cmd *cmd);
637 static void transport_complete_qf(struct se_cmd *cmd);
638
639 static void target_qf_do_work(struct work_struct *work)
640 {
641         struct se_device *dev = container_of(work, struct se_device,
642                                         qf_work_queue);
643         LIST_HEAD(qf_cmd_list);
644         struct se_cmd *cmd, *cmd_tmp;
645
646         spin_lock_irq(&dev->qf_cmd_lock);
647         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
648         spin_unlock_irq(&dev->qf_cmd_lock);
649
650         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
651                 list_del(&cmd->se_qf_node);
652                 atomic_dec(&dev->dev_qf_count);
653                 smp_mb__after_atomic_dec();
654
655                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
656                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
657                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
658                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
659                         : "UNKNOWN");
660
661                 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
662                         transport_write_pending_qf(cmd);
663                 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK)
664                         transport_complete_qf(cmd);
665         }
666 }
667
668 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
669 {
670         switch (cmd->data_direction) {
671         case DMA_NONE:
672                 return "NONE";
673         case DMA_FROM_DEVICE:
674                 return "READ";
675         case DMA_TO_DEVICE:
676                 return "WRITE";
677         case DMA_BIDIRECTIONAL:
678                 return "BIDI";
679         default:
680                 break;
681         }
682
683         return "UNKNOWN";
684 }
685
686 void transport_dump_dev_state(
687         struct se_device *dev,
688         char *b,
689         int *bl)
690 {
691         *bl += sprintf(b + *bl, "Status: ");
692         switch (dev->dev_status) {
693         case TRANSPORT_DEVICE_ACTIVATED:
694                 *bl += sprintf(b + *bl, "ACTIVATED");
695                 break;
696         case TRANSPORT_DEVICE_DEACTIVATED:
697                 *bl += sprintf(b + *bl, "DEACTIVATED");
698                 break;
699         case TRANSPORT_DEVICE_SHUTDOWN:
700                 *bl += sprintf(b + *bl, "SHUTDOWN");
701                 break;
702         case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
703         case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
704                 *bl += sprintf(b + *bl, "OFFLINE");
705                 break;
706         default:
707                 *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
708                 break;
709         }
710
711         *bl += sprintf(b + *bl, "  Max Queue Depth: %d", dev->queue_depth);
712         *bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
713                 dev->se_sub_dev->se_dev_attrib.block_size,
714                 dev->se_sub_dev->se_dev_attrib.hw_max_sectors);
715         *bl += sprintf(b + *bl, "        ");
716 }
717
718 void transport_dump_vpd_proto_id(
719         struct t10_vpd *vpd,
720         unsigned char *p_buf,
721         int p_buf_len)
722 {
723         unsigned char buf[VPD_TMP_BUF_SIZE];
724         int len;
725
726         memset(buf, 0, VPD_TMP_BUF_SIZE);
727         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
728
729         switch (vpd->protocol_identifier) {
730         case 0x00:
731                 sprintf(buf+len, "Fibre Channel\n");
732                 break;
733         case 0x10:
734                 sprintf(buf+len, "Parallel SCSI\n");
735                 break;
736         case 0x20:
737                 sprintf(buf+len, "SSA\n");
738                 break;
739         case 0x30:
740                 sprintf(buf+len, "IEEE 1394\n");
741                 break;
742         case 0x40:
743                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
744                                 " Protocol\n");
745                 break;
746         case 0x50:
747                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
748                 break;
749         case 0x60:
750                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
751                 break;
752         case 0x70:
753                 sprintf(buf+len, "Automation/Drive Interface Transport"
754                                 " Protocol\n");
755                 break;
756         case 0x80:
757                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
758                 break;
759         default:
760                 sprintf(buf+len, "Unknown 0x%02x\n",
761                                 vpd->protocol_identifier);
762                 break;
763         }
764
765         if (p_buf)
766                 strncpy(p_buf, buf, p_buf_len);
767         else
768                 pr_debug("%s", buf);
769 }
770
771 void
772 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
773 {
774         /*
775          * Check if the Protocol Identifier Valid (PIV) bit is set..
776          *
777          * from spc3r23.pdf section 7.5.1
778          */
779          if (page_83[1] & 0x80) {
780                 vpd->protocol_identifier = (page_83[0] & 0xf0);
781                 vpd->protocol_identifier_set = 1;
782                 transport_dump_vpd_proto_id(vpd, NULL, 0);
783         }
784 }
785 EXPORT_SYMBOL(transport_set_vpd_proto_id);
786
787 int transport_dump_vpd_assoc(
788         struct t10_vpd *vpd,
789         unsigned char *p_buf,
790         int p_buf_len)
791 {
792         unsigned char buf[VPD_TMP_BUF_SIZE];
793         int ret = 0;
794         int len;
795
796         memset(buf, 0, VPD_TMP_BUF_SIZE);
797         len = sprintf(buf, "T10 VPD Identifier Association: ");
798
799         switch (vpd->association) {
800         case 0x00:
801                 sprintf(buf+len, "addressed logical unit\n");
802                 break;
803         case 0x10:
804                 sprintf(buf+len, "target port\n");
805                 break;
806         case 0x20:
807                 sprintf(buf+len, "SCSI target device\n");
808                 break;
809         default:
810                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
811                 ret = -EINVAL;
812                 break;
813         }
814
815         if (p_buf)
816                 strncpy(p_buf, buf, p_buf_len);
817         else
818                 pr_debug("%s", buf);
819
820         return ret;
821 }
822
823 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
824 {
825         /*
826          * The VPD identification association..
827          *
828          * from spc3r23.pdf Section 7.6.3.1 Table 297
829          */
830         vpd->association = (page_83[1] & 0x30);
831         return transport_dump_vpd_assoc(vpd, NULL, 0);
832 }
833 EXPORT_SYMBOL(transport_set_vpd_assoc);
834
835 int transport_dump_vpd_ident_type(
836         struct t10_vpd *vpd,
837         unsigned char *p_buf,
838         int p_buf_len)
839 {
840         unsigned char buf[VPD_TMP_BUF_SIZE];
841         int ret = 0;
842         int len;
843
844         memset(buf, 0, VPD_TMP_BUF_SIZE);
845         len = sprintf(buf, "T10 VPD Identifier Type: ");
846
847         switch (vpd->device_identifier_type) {
848         case 0x00:
849                 sprintf(buf+len, "Vendor specific\n");
850                 break;
851         case 0x01:
852                 sprintf(buf+len, "T10 Vendor ID based\n");
853                 break;
854         case 0x02:
855                 sprintf(buf+len, "EUI-64 based\n");
856                 break;
857         case 0x03:
858                 sprintf(buf+len, "NAA\n");
859                 break;
860         case 0x04:
861                 sprintf(buf+len, "Relative target port identifier\n");
862                 break;
863         case 0x08:
864                 sprintf(buf+len, "SCSI name string\n");
865                 break;
866         default:
867                 sprintf(buf+len, "Unsupported: 0x%02x\n",
868                                 vpd->device_identifier_type);
869                 ret = -EINVAL;
870                 break;
871         }
872
873         if (p_buf) {
874                 if (p_buf_len < strlen(buf)+1)
875                         return -EINVAL;
876                 strncpy(p_buf, buf, p_buf_len);
877         } else {
878                 pr_debug("%s", buf);
879         }
880
881         return ret;
882 }
883
884 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
885 {
886         /*
887          * The VPD identifier type..
888          *
889          * from spc3r23.pdf Section 7.6.3.1 Table 298
890          */
891         vpd->device_identifier_type = (page_83[1] & 0x0f);
892         return transport_dump_vpd_ident_type(vpd, NULL, 0);
893 }
894 EXPORT_SYMBOL(transport_set_vpd_ident_type);
895
896 int transport_dump_vpd_ident(
897         struct t10_vpd *vpd,
898         unsigned char *p_buf,
899         int p_buf_len)
900 {
901         unsigned char buf[VPD_TMP_BUF_SIZE];
902         int ret = 0;
903
904         memset(buf, 0, VPD_TMP_BUF_SIZE);
905
906         switch (vpd->device_identifier_code_set) {
907         case 0x01: /* Binary */
908                 sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
909                         &vpd->device_identifier[0]);
910                 break;
911         case 0x02: /* ASCII */
912                 sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
913                         &vpd->device_identifier[0]);
914                 break;
915         case 0x03: /* UTF-8 */
916                 sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
917                         &vpd->device_identifier[0]);
918                 break;
919         default:
920                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
921                         " 0x%02x", vpd->device_identifier_code_set);
922                 ret = -EINVAL;
923                 break;
924         }
925
926         if (p_buf)
927                 strncpy(p_buf, buf, p_buf_len);
928         else
929                 pr_debug("%s", buf);
930
931         return ret;
932 }
933
934 int
935 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
936 {
937         static const char hex_str[] = "0123456789abcdef";
938         int j = 0, i = 4; /* offset to start of the identifier */
939
940         /*
941          * The VPD Code Set (encoding)
942          *
943          * from spc3r23.pdf Section 7.6.3.1 Table 296
944          */
945         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
946         switch (vpd->device_identifier_code_set) {
947         case 0x01: /* Binary */
948                 vpd->device_identifier[j++] =
949                                 hex_str[vpd->device_identifier_type];
950                 while (i < (4 + page_83[3])) {
951                         vpd->device_identifier[j++] =
952                                 hex_str[(page_83[i] & 0xf0) >> 4];
953                         vpd->device_identifier[j++] =
954                                 hex_str[page_83[i] & 0x0f];
955                         i++;
956                 }
957                 break;
958         case 0x02: /* ASCII */
959         case 0x03: /* UTF-8 */
960                 while (i < (4 + page_83[3]))
961                         vpd->device_identifier[j++] = page_83[i++];
962                 break;
963         default:
964                 break;
965         }
966
967         return transport_dump_vpd_ident(vpd, NULL, 0);
968 }
969 EXPORT_SYMBOL(transport_set_vpd_ident);
970
971 static void core_setup_task_attr_emulation(struct se_device *dev)
972 {
973         /*
974          * If this device is from Target_Core_Mod/pSCSI, disable the
975          * SAM Task Attribute emulation.
976          *
977          * This is currently not available in upsream Linux/SCSI Target
978          * mode code, and is assumed to be disabled while using TCM/pSCSI.
979          */
980         if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
981                 dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
982                 return;
983         }
984
985         dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
986         pr_debug("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
987                 " device\n", dev->transport->name,
988                 dev->transport->get_device_rev(dev));
989 }
990
991 static void scsi_dump_inquiry(struct se_device *dev)
992 {
993         struct t10_wwn *wwn = &dev->se_sub_dev->t10_wwn;
994         char buf[17];
995         int i, device_type;
996         /*
997          * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
998          */
999         for (i = 0; i < 8; i++)
1000                 if (wwn->vendor[i] >= 0x20)
1001                         buf[i] = wwn->vendor[i];
1002                 else
1003                         buf[i] = ' ';
1004         buf[i] = '\0';
1005         pr_debug("  Vendor: %s\n", buf);
1006
1007         for (i = 0; i < 16; i++)
1008                 if (wwn->model[i] >= 0x20)
1009                         buf[i] = wwn->model[i];
1010                 else
1011                         buf[i] = ' ';
1012         buf[i] = '\0';
1013         pr_debug("  Model: %s\n", buf);
1014
1015         for (i = 0; i < 4; i++)
1016                 if (wwn->revision[i] >= 0x20)
1017                         buf[i] = wwn->revision[i];
1018                 else
1019                         buf[i] = ' ';
1020         buf[i] = '\0';
1021         pr_debug("  Revision: %s\n", buf);
1022
1023         device_type = dev->transport->get_device_type(dev);
1024         pr_debug("  Type:   %s ", scsi_device_type(device_type));
1025         pr_debug("                 ANSI SCSI revision: %02x\n",
1026                                 dev->transport->get_device_rev(dev));
1027 }
1028
1029 struct se_device *transport_add_device_to_core_hba(
1030         struct se_hba *hba,
1031         struct se_subsystem_api *transport,
1032         struct se_subsystem_dev *se_dev,
1033         u32 device_flags,
1034         void *transport_dev,
1035         struct se_dev_limits *dev_limits,
1036         const char *inquiry_prod,
1037         const char *inquiry_rev)
1038 {
1039         int force_pt;
1040         struct se_device  *dev;
1041
1042         dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1043         if (!dev) {
1044                 pr_err("Unable to allocate memory for se_dev_t\n");
1045                 return NULL;
1046         }
1047
1048         dev->dev_flags          = device_flags;
1049         dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1050         dev->dev_ptr            = transport_dev;
1051         dev->se_hba             = hba;
1052         dev->se_sub_dev         = se_dev;
1053         dev->transport          = transport;
1054         INIT_LIST_HEAD(&dev->dev_list);
1055         INIT_LIST_HEAD(&dev->dev_sep_list);
1056         INIT_LIST_HEAD(&dev->dev_tmr_list);
1057         INIT_LIST_HEAD(&dev->delayed_cmd_list);
1058         INIT_LIST_HEAD(&dev->state_list);
1059         INIT_LIST_HEAD(&dev->qf_cmd_list);
1060         spin_lock_init(&dev->execute_task_lock);
1061         spin_lock_init(&dev->delayed_cmd_lock);
1062         spin_lock_init(&dev->dev_reservation_lock);
1063         spin_lock_init(&dev->dev_status_lock);
1064         spin_lock_init(&dev->se_port_lock);
1065         spin_lock_init(&dev->se_tmr_lock);
1066         spin_lock_init(&dev->qf_cmd_lock);
1067         atomic_set(&dev->dev_ordered_id, 0);
1068
1069         se_dev_set_default_attribs(dev, dev_limits);
1070
1071         dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1072         dev->creation_time = get_jiffies_64();
1073         spin_lock_init(&dev->stats_lock);
1074
1075         spin_lock(&hba->device_lock);
1076         list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1077         hba->dev_count++;
1078         spin_unlock(&hba->device_lock);
1079         /*
1080          * Setup the SAM Task Attribute emulation for struct se_device
1081          */
1082         core_setup_task_attr_emulation(dev);
1083         /*
1084          * Force PR and ALUA passthrough emulation with internal object use.
1085          */
1086         force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1087         /*
1088          * Setup the Reservations infrastructure for struct se_device
1089          */
1090         core_setup_reservations(dev, force_pt);
1091         /*
1092          * Setup the Asymmetric Logical Unit Assignment for struct se_device
1093          */
1094         if (core_setup_alua(dev, force_pt) < 0)
1095                 goto err_dev_list;
1096
1097         /*
1098          * Startup the struct se_device processing thread
1099          */
1100         dev->tmr_wq = alloc_workqueue("tmr-%s", WQ_MEM_RECLAIM | WQ_UNBOUND, 1,
1101                                       dev->transport->name);
1102         if (!dev->tmr_wq) {
1103                 pr_err("Unable to create tmr workqueue for %s\n",
1104                         dev->transport->name);
1105                 goto err_dev_list;
1106         }
1107         /*
1108          * Setup work_queue for QUEUE_FULL
1109          */
1110         INIT_WORK(&dev->qf_work_queue, target_qf_do_work);
1111         /*
1112          * Preload the initial INQUIRY const values if we are doing
1113          * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1114          * passthrough because this is being provided by the backend LLD.
1115          * This is required so that transport_get_inquiry() copies these
1116          * originals once back into DEV_T10_WWN(dev) for the virtual device
1117          * setup.
1118          */
1119         if (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1120                 if (!inquiry_prod || !inquiry_rev) {
1121                         pr_err("All non TCM/pSCSI plugins require"
1122                                 " INQUIRY consts\n");
1123                         goto err_wq;
1124                 }
1125
1126                 strncpy(&dev->se_sub_dev->t10_wwn.vendor[0], "LIO-ORG", 8);
1127                 strncpy(&dev->se_sub_dev->t10_wwn.model[0], inquiry_prod, 16);
1128                 strncpy(&dev->se_sub_dev->t10_wwn.revision[0], inquiry_rev, 4);
1129         }
1130         scsi_dump_inquiry(dev);
1131
1132         return dev;
1133
1134 err_wq:
1135         destroy_workqueue(dev->tmr_wq);
1136 err_dev_list:
1137         spin_lock(&hba->device_lock);
1138         list_del(&dev->dev_list);
1139         hba->dev_count--;
1140         spin_unlock(&hba->device_lock);
1141
1142         se_release_vpd_for_dev(dev);
1143
1144         kfree(dev);
1145
1146         return NULL;
1147 }
1148 EXPORT_SYMBOL(transport_add_device_to_core_hba);
1149
1150 int target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1151 {
1152         struct se_device *dev = cmd->se_dev;
1153
1154         if (cmd->unknown_data_length) {
1155                 cmd->data_length = size;
1156         } else if (size != cmd->data_length) {
1157                 pr_warn("TARGET_CORE[%s]: Expected Transfer Length:"
1158                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1159                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
1160                                 cmd->data_length, size, cmd->t_task_cdb[0]);
1161
1162                 if (cmd->data_direction == DMA_TO_DEVICE) {
1163                         pr_err("Rejecting underflow/overflow"
1164                                         " WRITE data\n");
1165                         goto out_invalid_cdb_field;
1166                 }
1167                 /*
1168                  * Reject READ_* or WRITE_* with overflow/underflow for
1169                  * type SCF_SCSI_DATA_CDB.
1170                  */
1171                 if (dev->se_sub_dev->se_dev_attrib.block_size != 512)  {
1172                         pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1173                                 " CDB on non 512-byte sector setup subsystem"
1174                                 " plugin: %s\n", dev->transport->name);
1175                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1176                         goto out_invalid_cdb_field;
1177                 }
1178
1179                 if (size > cmd->data_length) {
1180                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1181                         cmd->residual_count = (size - cmd->data_length);
1182                 } else {
1183                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1184                         cmd->residual_count = (cmd->data_length - size);
1185                 }
1186                 cmd->data_length = size;
1187         }
1188
1189         return 0;
1190
1191 out_invalid_cdb_field:
1192         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1193         cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1194         return -EINVAL;
1195 }
1196
1197 /*
1198  * Used by fabric modules containing a local struct se_cmd within their
1199  * fabric dependent per I/O descriptor.
1200  */
1201 void transport_init_se_cmd(
1202         struct se_cmd *cmd,
1203         struct target_core_fabric_ops *tfo,
1204         struct se_session *se_sess,
1205         u32 data_length,
1206         int data_direction,
1207         int task_attr,
1208         unsigned char *sense_buffer)
1209 {
1210         INIT_LIST_HEAD(&cmd->se_lun_node);
1211         INIT_LIST_HEAD(&cmd->se_delayed_node);
1212         INIT_LIST_HEAD(&cmd->se_qf_node);
1213         INIT_LIST_HEAD(&cmd->se_cmd_list);
1214         INIT_LIST_HEAD(&cmd->state_list);
1215         init_completion(&cmd->transport_lun_fe_stop_comp);
1216         init_completion(&cmd->transport_lun_stop_comp);
1217         init_completion(&cmd->t_transport_stop_comp);
1218         init_completion(&cmd->cmd_wait_comp);
1219         init_completion(&cmd->task_stop_comp);
1220         spin_lock_init(&cmd->t_state_lock);
1221         cmd->transport_state = CMD_T_DEV_ACTIVE;
1222
1223         cmd->se_tfo = tfo;
1224         cmd->se_sess = se_sess;
1225         cmd->data_length = data_length;
1226         cmd->data_direction = data_direction;
1227         cmd->sam_task_attr = task_attr;
1228         cmd->sense_buffer = sense_buffer;
1229
1230         cmd->state_active = false;
1231 }
1232 EXPORT_SYMBOL(transport_init_se_cmd);
1233
1234 static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1235 {
1236         /*
1237          * Check if SAM Task Attribute emulation is enabled for this
1238          * struct se_device storage object
1239          */
1240         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1241                 return 0;
1242
1243         if (cmd->sam_task_attr == MSG_ACA_TAG) {
1244                 pr_debug("SAM Task Attribute ACA"
1245                         " emulation is not supported\n");
1246                 return -EINVAL;
1247         }
1248         /*
1249          * Used to determine when ORDERED commands should go from
1250          * Dormant to Active status.
1251          */
1252         cmd->se_ordered_id = atomic_inc_return(&cmd->se_dev->dev_ordered_id);
1253         smp_mb__after_atomic_inc();
1254         pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1255                         cmd->se_ordered_id, cmd->sam_task_attr,
1256                         cmd->se_dev->transport->name);
1257         return 0;
1258 }
1259
1260 /*      target_setup_cmd_from_cdb():
1261  *
1262  *      Called from fabric RX Thread.
1263  */
1264 int target_setup_cmd_from_cdb(
1265         struct se_cmd *cmd,
1266         unsigned char *cdb)
1267 {
1268         struct se_subsystem_dev *su_dev = cmd->se_dev->se_sub_dev;
1269         u32 pr_reg_type = 0;
1270         u8 alua_ascq = 0;
1271         unsigned long flags;
1272         int ret;
1273
1274         /*
1275          * Ensure that the received CDB is less than the max (252 + 8) bytes
1276          * for VARIABLE_LENGTH_CMD
1277          */
1278         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1279                 pr_err("Received SCSI CDB with command_size: %d that"
1280                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1281                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1282                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1283                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1284                 return -EINVAL;
1285         }
1286         /*
1287          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1288          * allocate the additional extended CDB buffer now..  Otherwise
1289          * setup the pointer from __t_task_cdb to t_task_cdb.
1290          */
1291         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1292                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1293                                                 GFP_KERNEL);
1294                 if (!cmd->t_task_cdb) {
1295                         pr_err("Unable to allocate cmd->t_task_cdb"
1296                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1297                                 scsi_command_size(cdb),
1298                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1299                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1300                         cmd->scsi_sense_reason =
1301                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1302                         return -ENOMEM;
1303                 }
1304         } else
1305                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1306         /*
1307          * Copy the original CDB into cmd->
1308          */
1309         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1310
1311         /*
1312          * Check for an existing UNIT ATTENTION condition
1313          */
1314         if (core_scsi3_ua_check(cmd, cdb) < 0) {
1315                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1316                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
1317                 return -EINVAL;
1318         }
1319
1320         ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
1321         if (ret != 0) {
1322                 /*
1323                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
1324                  * The ALUA additional sense code qualifier (ASCQ) is determined
1325                  * by the ALUA primary or secondary access state..
1326                  */
1327                 if (ret > 0) {
1328                         pr_debug("[%s]: ALUA TG Port not available, "
1329                                 "SenseKey: NOT_READY, ASC/ASCQ: "
1330                                 "0x04/0x%02x\n",
1331                                 cmd->se_tfo->get_fabric_name(), alua_ascq);
1332
1333                         transport_set_sense_codes(cmd, 0x04, alua_ascq);
1334                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1335                         cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
1336                         return -EINVAL;
1337                 }
1338                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1339                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1340                 return -EINVAL;
1341         }
1342
1343         /*
1344          * Check status for SPC-3 Persistent Reservations
1345          */
1346         if (su_dev->t10_pr.pr_ops.t10_reservation_check(cmd, &pr_reg_type)) {
1347                 if (su_dev->t10_pr.pr_ops.t10_seq_non_holder(
1348                                         cmd, cdb, pr_reg_type) != 0) {
1349                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1350                         cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
1351                         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1352                         cmd->scsi_sense_reason = TCM_RESERVATION_CONFLICT;
1353                         return -EBUSY;
1354                 }
1355                 /*
1356                  * This means the CDB is allowed for the SCSI Initiator port
1357                  * when said port is *NOT* holding the legacy SPC-2 or
1358                  * SPC-3 Persistent Reservation.
1359                  */
1360         }
1361
1362         ret = cmd->se_dev->transport->parse_cdb(cmd);
1363         if (ret < 0)
1364                 return ret;
1365
1366         spin_lock_irqsave(&cmd->t_state_lock, flags);
1367         cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1368         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1369
1370         /*
1371          * Check for SAM Task Attribute Emulation
1372          */
1373         if (transport_check_alloc_task_attr(cmd) < 0) {
1374                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1375                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1376                 return -EINVAL;
1377         }
1378         spin_lock(&cmd->se_lun->lun_sep_lock);
1379         if (cmd->se_lun->lun_sep)
1380                 cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1381         spin_unlock(&cmd->se_lun->lun_sep_lock);
1382         return 0;
1383 }
1384 EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1385
1386 /*
1387  * Used by fabric module frontends to queue tasks directly.
1388  * Many only be used from process context only
1389  */
1390 int transport_handle_cdb_direct(
1391         struct se_cmd *cmd)
1392 {
1393         int ret;
1394
1395         if (!cmd->se_lun) {
1396                 dump_stack();
1397                 pr_err("cmd->se_lun is NULL\n");
1398                 return -EINVAL;
1399         }
1400         if (in_interrupt()) {
1401                 dump_stack();
1402                 pr_err("transport_generic_handle_cdb cannot be called"
1403                                 " from interrupt context\n");
1404                 return -EINVAL;
1405         }
1406         /*
1407          * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1408          * outstanding descriptors are handled correctly during shutdown via
1409          * transport_wait_for_tasks()
1410          *
1411          * Also, we don't take cmd->t_state_lock here as we only expect
1412          * this to be called for initial descriptor submission.
1413          */
1414         cmd->t_state = TRANSPORT_NEW_CMD;
1415         cmd->transport_state |= CMD_T_ACTIVE;
1416
1417         /*
1418          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1419          * so follow TRANSPORT_NEW_CMD processing thread context usage
1420          * and call transport_generic_request_failure() if necessary..
1421          */
1422         ret = transport_generic_new_cmd(cmd);
1423         if (ret < 0)
1424                 transport_generic_request_failure(cmd);
1425
1426         return 0;
1427 }
1428 EXPORT_SYMBOL(transport_handle_cdb_direct);
1429
1430 /**
1431  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1432  *
1433  * @se_cmd: command descriptor to submit
1434  * @se_sess: associated se_sess for endpoint
1435  * @cdb: pointer to SCSI CDB
1436  * @sense: pointer to SCSI sense buffer
1437  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1438  * @data_length: fabric expected data transfer length
1439  * @task_addr: SAM task attribute
1440  * @data_dir: DMA data direction
1441  * @flags: flags for command submission from target_sc_flags_tables
1442  *
1443  * Returns non zero to signal active I/O shutdown failure.  All other
1444  * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1445  * but still return zero here.
1446  *
1447  * This may only be called from process context, and also currently
1448  * assumes internal allocation of fabric payload buffer by target-core.
1449  **/
1450 int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1451                 unsigned char *cdb, unsigned char *sense, u32 unpacked_lun,
1452                 u32 data_length, int task_attr, int data_dir, int flags)
1453 {
1454         struct se_portal_group *se_tpg;
1455         int rc;
1456
1457         se_tpg = se_sess->se_tpg;
1458         BUG_ON(!se_tpg);
1459         BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1460         BUG_ON(in_interrupt());
1461         /*
1462          * Initialize se_cmd for target operation.  From this point
1463          * exceptions are handled by sending exception status via
1464          * target_core_fabric_ops->queue_status() callback
1465          */
1466         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1467                                 data_length, data_dir, task_attr, sense);
1468         if (flags & TARGET_SCF_UNKNOWN_SIZE)
1469                 se_cmd->unknown_data_length = 1;
1470         /*
1471          * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1472          * se_sess->sess_cmd_list.  A second kref_get here is necessary
1473          * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1474          * kref_put() to happen during fabric packet acknowledgement.
1475          */
1476         rc = target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1477         if (rc)
1478                 return rc;
1479         /*
1480          * Signal bidirectional data payloads to target-core
1481          */
1482         if (flags & TARGET_SCF_BIDI_OP)
1483                 se_cmd->se_cmd_flags |= SCF_BIDI;
1484         /*
1485          * Locate se_lun pointer and attach it to struct se_cmd
1486          */
1487         if (transport_lookup_cmd_lun(se_cmd, unpacked_lun) < 0) {
1488                 transport_send_check_condition_and_sense(se_cmd,
1489                                 se_cmd->scsi_sense_reason, 0);
1490                 target_put_sess_cmd(se_sess, se_cmd);
1491                 return 0;
1492         }
1493
1494         rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1495         if (rc != 0) {
1496                 transport_generic_request_failure(se_cmd);
1497                 return 0;
1498         }
1499
1500         /*
1501          * Check if we need to delay processing because of ALUA
1502          * Active/NonOptimized primary access state..
1503          */
1504         core_alua_check_nonop_delay(se_cmd);
1505
1506         transport_handle_cdb_direct(se_cmd);
1507         return 0;
1508 }
1509 EXPORT_SYMBOL(target_submit_cmd);
1510
1511 static void target_complete_tmr_failure(struct work_struct *work)
1512 {
1513         struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1514
1515         se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1516         se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1517         transport_generic_free_cmd(se_cmd, 0);
1518 }
1519
1520 /**
1521  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1522  *                     for TMR CDBs
1523  *
1524  * @se_cmd: command descriptor to submit
1525  * @se_sess: associated se_sess for endpoint
1526  * @sense: pointer to SCSI sense buffer
1527  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1528  * @fabric_context: fabric context for TMR req
1529  * @tm_type: Type of TM request
1530  * @gfp: gfp type for caller
1531  * @tag: referenced task tag for TMR_ABORT_TASK
1532  * @flags: submit cmd flags
1533  *
1534  * Callable from all contexts.
1535  **/
1536
1537 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1538                 unsigned char *sense, u32 unpacked_lun,
1539                 void *fabric_tmr_ptr, unsigned char tm_type,
1540                 gfp_t gfp, unsigned int tag, int flags)
1541 {
1542         struct se_portal_group *se_tpg;
1543         int ret;
1544
1545         se_tpg = se_sess->se_tpg;
1546         BUG_ON(!se_tpg);
1547
1548         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1549                               0, DMA_NONE, MSG_SIMPLE_TAG, sense);
1550         /*
1551          * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1552          * allocation failure.
1553          */
1554         ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1555         if (ret < 0)
1556                 return -ENOMEM;
1557
1558         if (tm_type == TMR_ABORT_TASK)
1559                 se_cmd->se_tmr_req->ref_task_tag = tag;
1560
1561         /* See target_submit_cmd for commentary */
1562         ret = target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1563         if (ret) {
1564                 core_tmr_release_req(se_cmd->se_tmr_req);
1565                 return ret;
1566         }
1567
1568         ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1569         if (ret) {
1570                 /*
1571                  * For callback during failure handling, push this work off
1572                  * to process context with TMR_LUN_DOES_NOT_EXIST status.
1573                  */
1574                 INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1575                 schedule_work(&se_cmd->work);
1576                 return 0;
1577         }
1578         transport_generic_handle_tmr(se_cmd);
1579         return 0;
1580 }
1581 EXPORT_SYMBOL(target_submit_tmr);
1582
1583 /*
1584  * If the cmd is active, request it to be stopped and sleep until it
1585  * has completed.
1586  */
1587 bool target_stop_cmd(struct se_cmd *cmd, unsigned long *flags)
1588 {
1589         bool was_active = false;
1590
1591         if (cmd->transport_state & CMD_T_BUSY) {
1592                 cmd->transport_state |= CMD_T_REQUEST_STOP;
1593                 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
1594
1595                 pr_debug("cmd %p waiting to complete\n", cmd);
1596                 wait_for_completion(&cmd->task_stop_comp);
1597                 pr_debug("cmd %p stopped successfully\n", cmd);
1598
1599                 spin_lock_irqsave(&cmd->t_state_lock, *flags);
1600                 cmd->transport_state &= ~CMD_T_REQUEST_STOP;
1601                 cmd->transport_state &= ~CMD_T_BUSY;
1602                 was_active = true;
1603         }
1604
1605         return was_active;
1606 }
1607
1608 /*
1609  * Handle SAM-esque emulation for generic transport request failures.
1610  */
1611 void transport_generic_request_failure(struct se_cmd *cmd)
1612 {
1613         int ret = 0;
1614
1615         pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1616                 " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
1617                 cmd->t_task_cdb[0]);
1618         pr_debug("-----[ i_state: %d t_state: %d scsi_sense_reason: %d\n",
1619                 cmd->se_tfo->get_cmd_state(cmd),
1620                 cmd->t_state, cmd->scsi_sense_reason);
1621         pr_debug("-----[ CMD_T_ACTIVE: %d CMD_T_STOP: %d CMD_T_SENT: %d\n",
1622                 (cmd->transport_state & CMD_T_ACTIVE) != 0,
1623                 (cmd->transport_state & CMD_T_STOP) != 0,
1624                 (cmd->transport_state & CMD_T_SENT) != 0);
1625
1626         /*
1627          * For SAM Task Attribute emulation for failed struct se_cmd
1628          */
1629         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1630                 transport_complete_task_attr(cmd);
1631
1632         switch (cmd->scsi_sense_reason) {
1633         case TCM_NON_EXISTENT_LUN:
1634         case TCM_UNSUPPORTED_SCSI_OPCODE:
1635         case TCM_INVALID_CDB_FIELD:
1636         case TCM_INVALID_PARAMETER_LIST:
1637         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1638         case TCM_UNKNOWN_MODE_PAGE:
1639         case TCM_WRITE_PROTECTED:
1640         case TCM_ADDRESS_OUT_OF_RANGE:
1641         case TCM_CHECK_CONDITION_ABORT_CMD:
1642         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1643         case TCM_CHECK_CONDITION_NOT_READY:
1644                 break;
1645         case TCM_RESERVATION_CONFLICT:
1646                 /*
1647                  * No SENSE Data payload for this case, set SCSI Status
1648                  * and queue the response to $FABRIC_MOD.
1649                  *
1650                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1651                  */
1652                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1653                 /*
1654                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1655                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1656                  * CONFLICT STATUS.
1657                  *
1658                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1659                  */
1660                 if (cmd->se_sess &&
1661                     cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
1662                         core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
1663                                 cmd->orig_fe_lun, 0x2C,
1664                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1665
1666                 ret = cmd->se_tfo->queue_status(cmd);
1667                 if (ret == -EAGAIN || ret == -ENOMEM)
1668                         goto queue_full;
1669                 goto check_stop;
1670         default:
1671                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1672                         cmd->t_task_cdb[0], cmd->scsi_sense_reason);
1673                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1674                 break;
1675         }
1676
1677         ret = transport_send_check_condition_and_sense(cmd,
1678                         cmd->scsi_sense_reason, 0);
1679         if (ret == -EAGAIN || ret == -ENOMEM)
1680                 goto queue_full;
1681
1682 check_stop:
1683         transport_lun_remove_cmd(cmd);
1684         if (!transport_cmd_check_stop_to_fabric(cmd))
1685                 ;
1686         return;
1687
1688 queue_full:
1689         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
1690         transport_handle_queue_full(cmd, cmd->se_dev);
1691 }
1692 EXPORT_SYMBOL(transport_generic_request_failure);
1693
1694 static void __target_execute_cmd(struct se_cmd *cmd)
1695 {
1696         int error = 0;
1697
1698         spin_lock_irq(&cmd->t_state_lock);
1699         cmd->transport_state |= (CMD_T_BUSY|CMD_T_SENT);
1700         spin_unlock_irq(&cmd->t_state_lock);
1701
1702         if (cmd->execute_cmd)
1703                 error = cmd->execute_cmd(cmd);
1704
1705         if (error) {
1706                 spin_lock_irq(&cmd->t_state_lock);
1707                 cmd->transport_state &= ~(CMD_T_BUSY|CMD_T_SENT);
1708                 spin_unlock_irq(&cmd->t_state_lock);
1709
1710                 transport_generic_request_failure(cmd);
1711         }
1712 }
1713
1714 void target_execute_cmd(struct se_cmd *cmd)
1715 {
1716         struct se_device *dev = cmd->se_dev;
1717
1718         /*
1719          * If the received CDB has aleady been aborted stop processing it here.
1720          */
1721         if (transport_check_aborted_status(cmd, 1))
1722                 return;
1723
1724         /*
1725          * Determine if IOCTL context caller in requesting the stopping of this
1726          * command for LUN shutdown purposes.
1727          */
1728         spin_lock_irq(&cmd->t_state_lock);
1729         if (cmd->transport_state & CMD_T_LUN_STOP) {
1730                 pr_debug("%s:%d CMD_T_LUN_STOP for ITT: 0x%08x\n",
1731                         __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd));
1732
1733                 cmd->transport_state &= ~CMD_T_ACTIVE;
1734                 spin_unlock_irq(&cmd->t_state_lock);
1735                 complete(&cmd->transport_lun_stop_comp);
1736                 return;
1737         }
1738         /*
1739          * Determine if frontend context caller is requesting the stopping of
1740          * this command for frontend exceptions.
1741          */
1742         if (cmd->transport_state & CMD_T_STOP) {
1743                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n",
1744                         __func__, __LINE__,
1745                         cmd->se_tfo->get_task_tag(cmd));
1746
1747                 spin_unlock_irq(&cmd->t_state_lock);
1748                 complete(&cmd->t_transport_stop_comp);
1749                 return;
1750         }
1751
1752         cmd->t_state = TRANSPORT_PROCESSING;
1753         spin_unlock_irq(&cmd->t_state_lock);
1754
1755         if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1756                 goto execute;
1757
1758         /*
1759          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1760          * to allow the passed struct se_cmd list of tasks to the front of the list.
1761          */
1762         switch (cmd->sam_task_attr) {
1763         case MSG_HEAD_TAG:
1764                 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x, "
1765                          "se_ordered_id: %u\n",
1766                          cmd->t_task_cdb[0], cmd->se_ordered_id);
1767                 goto execute;
1768         case MSG_ORDERED_TAG:
1769                 atomic_inc(&dev->dev_ordered_sync);
1770                 smp_mb__after_atomic_inc();
1771
1772                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list, "
1773                          " se_ordered_id: %u\n",
1774                          cmd->t_task_cdb[0], cmd->se_ordered_id);
1775
1776                 /*
1777                  * Execute an ORDERED command if no other older commands
1778                  * exist that need to be completed first.
1779                  */
1780                 if (!atomic_read(&dev->simple_cmds))
1781                         goto execute;
1782                 break;
1783         default:
1784                 /*
1785                  * For SIMPLE and UNTAGGED Task Attribute commands
1786                  */
1787                 atomic_inc(&dev->simple_cmds);
1788                 smp_mb__after_atomic_inc();
1789                 break;
1790         }
1791
1792         if (atomic_read(&dev->dev_ordered_sync) != 0) {
1793                 spin_lock(&dev->delayed_cmd_lock);
1794                 list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
1795                 spin_unlock(&dev->delayed_cmd_lock);
1796
1797                 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to"
1798                         " delayed CMD list, se_ordered_id: %u\n",
1799                         cmd->t_task_cdb[0], cmd->sam_task_attr,
1800                         cmd->se_ordered_id);
1801                 return;
1802         }
1803
1804 execute:
1805         /*
1806          * Otherwise, no ORDERED task attributes exist..
1807          */
1808         __target_execute_cmd(cmd);
1809 }
1810 EXPORT_SYMBOL(target_execute_cmd);
1811
1812 /*
1813  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
1814  */
1815 static int transport_get_sense_data(struct se_cmd *cmd)
1816 {
1817         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
1818         struct se_device *dev = cmd->se_dev;
1819         unsigned long flags;
1820
1821         WARN_ON(!cmd->se_lun);
1822
1823         if (!dev)
1824                 return 0;
1825
1826         spin_lock_irqsave(&cmd->t_state_lock, flags);
1827         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
1828                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1829                 return 0;
1830         }
1831
1832         if (!(cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE))
1833                 goto out;
1834
1835         if (!dev->transport->get_sense_buffer) {
1836                 pr_err("dev->transport->get_sense_buffer is NULL\n");
1837                 goto out;
1838         }
1839
1840         sense_buffer = dev->transport->get_sense_buffer(cmd);
1841         if (!sense_buffer) {
1842                 pr_err("ITT 0x%08x cmd %p: Unable to locate"
1843                         " sense buffer for task with sense\n",
1844                         cmd->se_tfo->get_task_tag(cmd), cmd);
1845                 goto out;
1846         }
1847
1848         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1849
1850         memcpy(buffer, sense_buffer, TRANSPORT_SENSE_BUFFER);
1851         cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
1852
1853         pr_debug("HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x and sense\n",
1854                 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
1855         return 0;
1856
1857 out:
1858         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1859         return -1;
1860 }
1861
1862 /*
1863  * Process all commands up to the last received ORDERED task attribute which
1864  * requires another blocking boundary
1865  */
1866 static void target_restart_delayed_cmds(struct se_device *dev)
1867 {
1868         for (;;) {
1869                 struct se_cmd *cmd;
1870
1871                 spin_lock(&dev->delayed_cmd_lock);
1872                 if (list_empty(&dev->delayed_cmd_list)) {
1873                         spin_unlock(&dev->delayed_cmd_lock);
1874                         break;
1875                 }
1876
1877                 cmd = list_entry(dev->delayed_cmd_list.next,
1878                                  struct se_cmd, se_delayed_node);
1879                 list_del(&cmd->se_delayed_node);
1880                 spin_unlock(&dev->delayed_cmd_lock);
1881
1882                 __target_execute_cmd(cmd);
1883
1884                 if (cmd->sam_task_attr == MSG_ORDERED_TAG)
1885                         break;
1886         }
1887 }
1888
1889 /*
1890  * Called from I/O completion to determine which dormant/delayed
1891  * and ordered cmds need to have their tasks added to the execution queue.
1892  */
1893 static void transport_complete_task_attr(struct se_cmd *cmd)
1894 {
1895         struct se_device *dev = cmd->se_dev;
1896
1897         if (cmd->sam_task_attr == MSG_SIMPLE_TAG) {
1898                 atomic_dec(&dev->simple_cmds);
1899                 smp_mb__after_atomic_dec();
1900                 dev->dev_cur_ordered_id++;
1901                 pr_debug("Incremented dev->dev_cur_ordered_id: %u for"
1902                         " SIMPLE: %u\n", dev->dev_cur_ordered_id,
1903                         cmd->se_ordered_id);
1904         } else if (cmd->sam_task_attr == MSG_HEAD_TAG) {
1905                 dev->dev_cur_ordered_id++;
1906                 pr_debug("Incremented dev_cur_ordered_id: %u for"
1907                         " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
1908                         cmd->se_ordered_id);
1909         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
1910                 atomic_dec(&dev->dev_ordered_sync);
1911                 smp_mb__after_atomic_dec();
1912
1913                 dev->dev_cur_ordered_id++;
1914                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED:"
1915                         " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
1916         }
1917
1918         target_restart_delayed_cmds(dev);
1919 }
1920
1921 static void transport_complete_qf(struct se_cmd *cmd)
1922 {
1923         int ret = 0;
1924
1925         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1926                 transport_complete_task_attr(cmd);
1927
1928         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
1929                 ret = cmd->se_tfo->queue_status(cmd);
1930                 if (ret)
1931                         goto out;
1932         }
1933
1934         switch (cmd->data_direction) {
1935         case DMA_FROM_DEVICE:
1936                 ret = cmd->se_tfo->queue_data_in(cmd);
1937                 break;
1938         case DMA_TO_DEVICE:
1939                 if (cmd->t_bidi_data_sg) {
1940                         ret = cmd->se_tfo->queue_data_in(cmd);
1941                         if (ret < 0)
1942                                 break;
1943                 }
1944                 /* Fall through for DMA_TO_DEVICE */
1945         case DMA_NONE:
1946                 ret = cmd->se_tfo->queue_status(cmd);
1947                 break;
1948         default:
1949                 break;
1950         }
1951
1952 out:
1953         if (ret < 0) {
1954                 transport_handle_queue_full(cmd, cmd->se_dev);
1955                 return;
1956         }
1957         transport_lun_remove_cmd(cmd);
1958         transport_cmd_check_stop_to_fabric(cmd);
1959 }
1960
1961 static void transport_handle_queue_full(
1962         struct se_cmd *cmd,
1963         struct se_device *dev)
1964 {
1965         spin_lock_irq(&dev->qf_cmd_lock);
1966         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
1967         atomic_inc(&dev->dev_qf_count);
1968         smp_mb__after_atomic_inc();
1969         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
1970
1971         schedule_work(&cmd->se_dev->qf_work_queue);
1972 }
1973
1974 static void target_complete_ok_work(struct work_struct *work)
1975 {
1976         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
1977         int reason = 0, ret;
1978
1979         /*
1980          * Check if we need to move delayed/dormant tasks from cmds on the
1981          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
1982          * Attribute.
1983          */
1984         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1985                 transport_complete_task_attr(cmd);
1986         /*
1987          * Check to schedule QUEUE_FULL work, or execute an existing
1988          * cmd->transport_qf_callback()
1989          */
1990         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
1991                 schedule_work(&cmd->se_dev->qf_work_queue);
1992
1993         /*
1994          * Check if we need to retrieve a sense buffer from
1995          * the struct se_cmd in question.
1996          */
1997         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
1998                 if (transport_get_sense_data(cmd) < 0)
1999                         reason = TCM_NON_EXISTENT_LUN;
2000
2001                 if (cmd->scsi_status) {
2002                         ret = transport_send_check_condition_and_sense(
2003                                         cmd, reason, 1);
2004                         if (ret == -EAGAIN || ret == -ENOMEM)
2005                                 goto queue_full;
2006
2007                         transport_lun_remove_cmd(cmd);
2008                         transport_cmd_check_stop_to_fabric(cmd);
2009                         return;
2010                 }
2011         }
2012         /*
2013          * Check for a callback, used by amongst other things
2014          * XDWRITE_READ_10 emulation.
2015          */
2016         if (cmd->transport_complete_callback)
2017                 cmd->transport_complete_callback(cmd);
2018
2019         switch (cmd->data_direction) {
2020         case DMA_FROM_DEVICE:
2021                 spin_lock(&cmd->se_lun->lun_sep_lock);
2022                 if (cmd->se_lun->lun_sep) {
2023                         cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
2024                                         cmd->data_length;
2025                 }
2026                 spin_unlock(&cmd->se_lun->lun_sep_lock);
2027
2028                 ret = cmd->se_tfo->queue_data_in(cmd);
2029                 if (ret == -EAGAIN || ret == -ENOMEM)
2030                         goto queue_full;
2031                 break;
2032         case DMA_TO_DEVICE:
2033                 spin_lock(&cmd->se_lun->lun_sep_lock);
2034                 if (cmd->se_lun->lun_sep) {
2035                         cmd->se_lun->lun_sep->sep_stats.rx_data_octets +=
2036                                 cmd->data_length;
2037                 }
2038                 spin_unlock(&cmd->se_lun->lun_sep_lock);
2039                 /*
2040                  * Check if we need to send READ payload for BIDI-COMMAND
2041                  */
2042                 if (cmd->t_bidi_data_sg) {
2043                         spin_lock(&cmd->se_lun->lun_sep_lock);
2044                         if (cmd->se_lun->lun_sep) {
2045                                 cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
2046                                         cmd->data_length;
2047                         }
2048                         spin_unlock(&cmd->se_lun->lun_sep_lock);
2049                         ret = cmd->se_tfo->queue_data_in(cmd);
2050                         if (ret == -EAGAIN || ret == -ENOMEM)
2051                                 goto queue_full;
2052                         break;
2053                 }
2054                 /* Fall through for DMA_TO_DEVICE */
2055         case DMA_NONE:
2056                 ret = cmd->se_tfo->queue_status(cmd);
2057                 if (ret == -EAGAIN || ret == -ENOMEM)
2058                         goto queue_full;
2059                 break;
2060         default:
2061                 break;
2062         }
2063
2064         transport_lun_remove_cmd(cmd);
2065         transport_cmd_check_stop_to_fabric(cmd);
2066         return;
2067
2068 queue_full:
2069         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2070                 " data_direction: %d\n", cmd, cmd->data_direction);
2071         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
2072         transport_handle_queue_full(cmd, cmd->se_dev);
2073 }
2074
2075 static inline void transport_free_sgl(struct scatterlist *sgl, int nents)
2076 {
2077         struct scatterlist *sg;
2078         int count;
2079
2080         for_each_sg(sgl, sg, nents, count)
2081                 __free_page(sg_page(sg));
2082
2083         kfree(sgl);
2084 }
2085
2086 static inline void transport_free_pages(struct se_cmd *cmd)
2087 {
2088         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
2089                 return;
2090
2091         transport_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2092         cmd->t_data_sg = NULL;
2093         cmd->t_data_nents = 0;
2094
2095         transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2096         cmd->t_bidi_data_sg = NULL;
2097         cmd->t_bidi_data_nents = 0;
2098 }
2099
2100 /**
2101  * transport_release_cmd - free a command
2102  * @cmd:       command to free
2103  *
2104  * This routine unconditionally frees a command, and reference counting
2105  * or list removal must be done in the caller.
2106  */
2107 static void transport_release_cmd(struct se_cmd *cmd)
2108 {
2109         BUG_ON(!cmd->se_tfo);
2110
2111         if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2112                 core_tmr_release_req(cmd->se_tmr_req);
2113         if (cmd->t_task_cdb != cmd->__t_task_cdb)
2114                 kfree(cmd->t_task_cdb);
2115         /*
2116          * If this cmd has been setup with target_get_sess_cmd(), drop
2117          * the kref and call ->release_cmd() in kref callback.
2118          */
2119          if (cmd->check_release != 0) {
2120                 target_put_sess_cmd(cmd->se_sess, cmd);
2121                 return;
2122         }
2123         cmd->se_tfo->release_cmd(cmd);
2124 }
2125
2126 /**
2127  * transport_put_cmd - release a reference to a command
2128  * @cmd:       command to release
2129  *
2130  * This routine releases our reference to the command and frees it if possible.
2131  */
2132 static void transport_put_cmd(struct se_cmd *cmd)
2133 {
2134         unsigned long flags;
2135
2136         spin_lock_irqsave(&cmd->t_state_lock, flags);
2137         if (atomic_read(&cmd->t_fe_count)) {
2138                 if (!atomic_dec_and_test(&cmd->t_fe_count))
2139                         goto out_busy;
2140         }
2141
2142         if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
2143                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
2144                 target_remove_from_state_list(cmd);
2145         }
2146         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2147
2148         transport_free_pages(cmd);
2149         transport_release_cmd(cmd);
2150         return;
2151 out_busy:
2152         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2153 }
2154
2155 /*
2156  * transport_generic_map_mem_to_cmd - Use fabric-alloced pages instead of
2157  * allocating in the core.
2158  * @cmd:  Associated se_cmd descriptor
2159  * @mem:  SGL style memory for TCM WRITE / READ
2160  * @sg_mem_num: Number of SGL elements
2161  * @mem_bidi_in: SGL style memory for TCM BIDI READ
2162  * @sg_mem_bidi_num: Number of BIDI READ SGL elements
2163  *
2164  * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
2165  * of parameters.
2166  */
2167 int transport_generic_map_mem_to_cmd(
2168         struct se_cmd *cmd,
2169         struct scatterlist *sgl,
2170         u32 sgl_count,
2171         struct scatterlist *sgl_bidi,
2172         u32 sgl_bidi_count)
2173 {
2174         if (!sgl || !sgl_count)
2175                 return 0;
2176
2177         /*
2178          * Reject SCSI data overflow with map_mem_to_cmd() as incoming
2179          * scatterlists already have been set to follow what the fabric
2180          * passes for the original expected data transfer length.
2181          */
2182         if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
2183                 pr_warn("Rejecting SCSI DATA overflow for fabric using"
2184                         " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
2185                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2186                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
2187                 return -EINVAL;
2188         }
2189
2190         cmd->t_data_sg = sgl;
2191         cmd->t_data_nents = sgl_count;
2192
2193         if (sgl_bidi && sgl_bidi_count) {
2194                 cmd->t_bidi_data_sg = sgl_bidi;
2195                 cmd->t_bidi_data_nents = sgl_bidi_count;
2196         }
2197         cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
2198         return 0;
2199 }
2200 EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
2201
2202 void *transport_kmap_data_sg(struct se_cmd *cmd)
2203 {
2204         struct scatterlist *sg = cmd->t_data_sg;
2205         struct page **pages;
2206         int i;
2207
2208         BUG_ON(!sg);
2209         /*
2210          * We need to take into account a possible offset here for fabrics like
2211          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2212          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2213          */
2214         if (!cmd->t_data_nents)
2215                 return NULL;
2216         else if (cmd->t_data_nents == 1)
2217                 return kmap(sg_page(sg)) + sg->offset;
2218
2219         /* >1 page. use vmap */
2220         pages = kmalloc(sizeof(*pages) * cmd->t_data_nents, GFP_KERNEL);
2221         if (!pages)
2222                 return NULL;
2223
2224         /* convert sg[] to pages[] */
2225         for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2226                 pages[i] = sg_page(sg);
2227         }
2228
2229         cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2230         kfree(pages);
2231         if (!cmd->t_data_vmap)
2232                 return NULL;
2233
2234         return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2235 }
2236 EXPORT_SYMBOL(transport_kmap_data_sg);
2237
2238 void transport_kunmap_data_sg(struct se_cmd *cmd)
2239 {
2240         if (!cmd->t_data_nents) {
2241                 return;
2242         } else if (cmd->t_data_nents == 1) {
2243                 kunmap(sg_page(cmd->t_data_sg));
2244                 return;
2245         }
2246
2247         vunmap(cmd->t_data_vmap);
2248         cmd->t_data_vmap = NULL;
2249 }
2250 EXPORT_SYMBOL(transport_kunmap_data_sg);
2251
2252 static int
2253 transport_generic_get_mem(struct se_cmd *cmd)
2254 {
2255         u32 length = cmd->data_length;
2256         unsigned int nents;
2257         struct page *page;
2258         gfp_t zero_flag;
2259         int i = 0;
2260
2261         nents = DIV_ROUND_UP(length, PAGE_SIZE);
2262         cmd->t_data_sg = kmalloc(sizeof(struct scatterlist) * nents, GFP_KERNEL);
2263         if (!cmd->t_data_sg)
2264                 return -ENOMEM;
2265
2266         cmd->t_data_nents = nents;
2267         sg_init_table(cmd->t_data_sg, nents);
2268
2269         zero_flag = cmd->se_cmd_flags & SCF_SCSI_DATA_CDB ? 0 : __GFP_ZERO;
2270
2271         while (length) {
2272                 u32 page_len = min_t(u32, length, PAGE_SIZE);
2273                 page = alloc_page(GFP_KERNEL | zero_flag);
2274                 if (!page)
2275                         goto out;
2276
2277                 sg_set_page(&cmd->t_data_sg[i], page, page_len, 0);
2278                 length -= page_len;
2279                 i++;
2280         }
2281         return 0;
2282
2283 out:
2284         while (i > 0) {
2285                 i--;
2286                 __free_page(sg_page(&cmd->t_data_sg[i]));
2287         }
2288         kfree(cmd->t_data_sg);
2289         cmd->t_data_sg = NULL;
2290         return -ENOMEM;
2291 }
2292
2293 /*
2294  * Allocate any required resources to execute the command.  For writes we
2295  * might not have the payload yet, so notify the fabric via a call to
2296  * ->write_pending instead. Otherwise place it on the execution queue.
2297  */
2298 int transport_generic_new_cmd(struct se_cmd *cmd)
2299 {
2300         int ret = 0;
2301
2302         /*
2303          * Determine is the TCM fabric module has already allocated physical
2304          * memory, and is directly calling transport_generic_map_mem_to_cmd()
2305          * beforehand.
2306          */
2307         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2308             cmd->data_length) {
2309                 ret = transport_generic_get_mem(cmd);
2310                 if (ret < 0)
2311                         goto out_fail;
2312         }
2313         /*
2314          * If this command doesn't have any payload and we don't have to call
2315          * into the fabric for data transfers, go ahead and complete it right
2316          * away.
2317          */
2318         if (!cmd->data_length) {
2319                 spin_lock_irq(&cmd->t_state_lock);
2320                 cmd->t_state = TRANSPORT_COMPLETE;
2321                 cmd->transport_state |= CMD_T_ACTIVE;
2322                 spin_unlock_irq(&cmd->t_state_lock);
2323
2324                 if (cmd->t_task_cdb[0] == REQUEST_SENSE) {
2325                         u8 ua_asc = 0, ua_ascq = 0;
2326
2327                         core_scsi3_ua_clear_for_request_sense(cmd,
2328                                         &ua_asc, &ua_ascq);
2329                 }
2330
2331                 INIT_WORK(&cmd->work, target_complete_ok_work);
2332                 queue_work(target_completion_wq, &cmd->work);
2333                 return 0;
2334         }
2335
2336         atomic_inc(&cmd->t_fe_count);
2337
2338         /*
2339          * If this command is not a write we can execute it right here,
2340          * for write buffers we need to notify the fabric driver first
2341          * and let it call back once the write buffers are ready.
2342          */
2343         target_add_to_state_list(cmd);
2344         if (cmd->data_direction != DMA_TO_DEVICE) {
2345                 target_execute_cmd(cmd);
2346                 return 0;
2347         }
2348
2349         spin_lock_irq(&cmd->t_state_lock);
2350         cmd->t_state = TRANSPORT_WRITE_PENDING;
2351         spin_unlock_irq(&cmd->t_state_lock);
2352
2353         transport_cmd_check_stop(cmd, false);
2354
2355         ret = cmd->se_tfo->write_pending(cmd);
2356         if (ret == -EAGAIN || ret == -ENOMEM)
2357                 goto queue_full;
2358
2359         if (ret < 0)
2360                 return ret;
2361         return 1;
2362
2363 out_fail:
2364         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2365         cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2366         return -EINVAL;
2367 queue_full:
2368         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2369         cmd->t_state = TRANSPORT_COMPLETE_QF_WP;
2370         transport_handle_queue_full(cmd, cmd->se_dev);
2371         return 0;
2372 }
2373 EXPORT_SYMBOL(transport_generic_new_cmd);
2374
2375 static void transport_write_pending_qf(struct se_cmd *cmd)
2376 {
2377         int ret;
2378
2379         ret = cmd->se_tfo->write_pending(cmd);
2380         if (ret == -EAGAIN || ret == -ENOMEM) {
2381                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2382                          cmd);
2383                 transport_handle_queue_full(cmd, cmd->se_dev);
2384         }
2385 }
2386
2387 void transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2388 {
2389         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD)) {
2390                 if (wait_for_tasks && (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2391                          transport_wait_for_tasks(cmd);
2392
2393                 transport_release_cmd(cmd);
2394         } else {
2395                 if (wait_for_tasks)
2396                         transport_wait_for_tasks(cmd);
2397
2398                 core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
2399
2400                 if (cmd->se_lun)
2401                         transport_lun_remove_cmd(cmd);
2402
2403                 transport_put_cmd(cmd);
2404         }
2405 }
2406 EXPORT_SYMBOL(transport_generic_free_cmd);
2407
2408 /* target_get_sess_cmd - Add command to active ->sess_cmd_list
2409  * @se_sess:    session to reference
2410  * @se_cmd:     command descriptor to add
2411  * @ack_kref:   Signal that fabric will perform an ack target_put_sess_cmd()
2412  */
2413 static int target_get_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd,
2414                                bool ack_kref)
2415 {
2416         unsigned long flags;
2417         int ret = 0;
2418
2419         kref_init(&se_cmd->cmd_kref);
2420         /*
2421          * Add a second kref if the fabric caller is expecting to handle
2422          * fabric acknowledgement that requires two target_put_sess_cmd()
2423          * invocations before se_cmd descriptor release.
2424          */
2425         if (ack_kref == true) {
2426                 kref_get(&se_cmd->cmd_kref);
2427                 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2428         }
2429
2430         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2431         if (se_sess->sess_tearing_down) {
2432                 ret = -ESHUTDOWN;
2433                 goto out;
2434         }
2435         list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2436         se_cmd->check_release = 1;
2437
2438 out:
2439         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2440         return ret;
2441 }
2442
2443 static void target_release_cmd_kref(struct kref *kref)
2444 {
2445         struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2446         struct se_session *se_sess = se_cmd->se_sess;
2447         unsigned long flags;
2448
2449         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2450         if (list_empty(&se_cmd->se_cmd_list)) {
2451                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2452                 se_cmd->se_tfo->release_cmd(se_cmd);
2453                 return;
2454         }
2455         if (se_sess->sess_tearing_down && se_cmd->cmd_wait_set) {
2456                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2457                 complete(&se_cmd->cmd_wait_comp);
2458                 return;
2459         }
2460         list_del(&se_cmd->se_cmd_list);
2461         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2462
2463         se_cmd->se_tfo->release_cmd(se_cmd);
2464 }
2465
2466 /* target_put_sess_cmd - Check for active I/O shutdown via kref_put
2467  * @se_sess:    session to reference
2468  * @se_cmd:     command descriptor to drop
2469  */
2470 int target_put_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd)
2471 {
2472         return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2473 }
2474 EXPORT_SYMBOL(target_put_sess_cmd);
2475
2476 /* target_sess_cmd_list_set_waiting - Flag all commands in
2477  *         sess_cmd_list to complete cmd_wait_comp.  Set
2478  *         sess_tearing_down so no more commands are queued.
2479  * @se_sess:    session to flag
2480  */
2481 void target_sess_cmd_list_set_waiting(struct se_session *se_sess)
2482 {
2483         struct se_cmd *se_cmd;
2484         unsigned long flags;
2485
2486         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2487
2488         WARN_ON(se_sess->sess_tearing_down);
2489         se_sess->sess_tearing_down = 1;
2490
2491         list_for_each_entry(se_cmd, &se_sess->sess_cmd_list, se_cmd_list)
2492                 se_cmd->cmd_wait_set = 1;
2493
2494         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2495 }
2496 EXPORT_SYMBOL(target_sess_cmd_list_set_waiting);
2497
2498 /* target_wait_for_sess_cmds - Wait for outstanding descriptors
2499  * @se_sess:    session to wait for active I/O
2500  * @wait_for_tasks:     Make extra transport_wait_for_tasks call
2501  */
2502 void target_wait_for_sess_cmds(
2503         struct se_session *se_sess,
2504         int wait_for_tasks)
2505 {
2506         struct se_cmd *se_cmd, *tmp_cmd;
2507         bool rc = false;
2508
2509         list_for_each_entry_safe(se_cmd, tmp_cmd,
2510                                 &se_sess->sess_cmd_list, se_cmd_list) {
2511                 list_del(&se_cmd->se_cmd_list);
2512
2513                 pr_debug("Waiting for se_cmd: %p t_state: %d, fabric state:"
2514                         " %d\n", se_cmd, se_cmd->t_state,
2515                         se_cmd->se_tfo->get_cmd_state(se_cmd));
2516
2517                 if (wait_for_tasks) {
2518                         pr_debug("Calling transport_wait_for_tasks se_cmd: %p t_state: %d,"
2519                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
2520                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
2521
2522                         rc = transport_wait_for_tasks(se_cmd);
2523
2524                         pr_debug("After transport_wait_for_tasks se_cmd: %p t_state: %d,"
2525                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
2526                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
2527                 }
2528
2529                 if (!rc) {
2530                         wait_for_completion(&se_cmd->cmd_wait_comp);
2531                         pr_debug("After cmd_wait_comp: se_cmd: %p t_state: %d"
2532                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
2533                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
2534                 }
2535
2536                 se_cmd->se_tfo->release_cmd(se_cmd);
2537         }
2538 }
2539 EXPORT_SYMBOL(target_wait_for_sess_cmds);
2540
2541 /*      transport_lun_wait_for_tasks():
2542  *
2543  *      Called from ConfigFS context to stop the passed struct se_cmd to allow
2544  *      an struct se_lun to be successfully shutdown.
2545  */
2546 static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
2547 {
2548         unsigned long flags;
2549         int ret = 0;
2550
2551         /*
2552          * If the frontend has already requested this struct se_cmd to
2553          * be stopped, we can safely ignore this struct se_cmd.
2554          */
2555         spin_lock_irqsave(&cmd->t_state_lock, flags);
2556         if (cmd->transport_state & CMD_T_STOP) {
2557                 cmd->transport_state &= ~CMD_T_LUN_STOP;
2558
2559                 pr_debug("ConfigFS ITT[0x%08x] - CMD_T_STOP, skipping\n",
2560                          cmd->se_tfo->get_task_tag(cmd));
2561                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2562                 transport_cmd_check_stop(cmd, false);
2563                 return -EPERM;
2564         }
2565         cmd->transport_state |= CMD_T_LUN_FE_STOP;
2566         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2567
2568         // XXX: audit task_flags checks.
2569         spin_lock_irqsave(&cmd->t_state_lock, flags);
2570         if ((cmd->transport_state & CMD_T_BUSY) &&
2571             (cmd->transport_state & CMD_T_SENT)) {
2572                 if (!target_stop_cmd(cmd, &flags))
2573                         ret++;
2574         }
2575         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2576
2577         pr_debug("ConfigFS: cmd: %p stop tasks ret:"
2578                         " %d\n", cmd, ret);
2579         if (!ret) {
2580                 pr_debug("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
2581                                 cmd->se_tfo->get_task_tag(cmd));
2582                 wait_for_completion(&cmd->transport_lun_stop_comp);
2583                 pr_debug("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
2584                                 cmd->se_tfo->get_task_tag(cmd));
2585         }
2586
2587         return 0;
2588 }
2589
2590 static void __transport_clear_lun_from_sessions(struct se_lun *lun)
2591 {
2592         struct se_cmd *cmd = NULL;
2593         unsigned long lun_flags, cmd_flags;
2594         /*
2595          * Do exception processing and return CHECK_CONDITION status to the
2596          * Initiator Port.
2597          */
2598         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2599         while (!list_empty(&lun->lun_cmd_list)) {
2600                 cmd = list_first_entry(&lun->lun_cmd_list,
2601                        struct se_cmd, se_lun_node);
2602                 list_del_init(&cmd->se_lun_node);
2603
2604                 spin_lock(&cmd->t_state_lock);
2605                 pr_debug("SE_LUN[%d] - Setting cmd->transport"
2606                         "_lun_stop for  ITT: 0x%08x\n",
2607                         cmd->se_lun->unpacked_lun,
2608                         cmd->se_tfo->get_task_tag(cmd));
2609                 cmd->transport_state |= CMD_T_LUN_STOP;
2610                 spin_unlock(&cmd->t_state_lock);
2611
2612                 spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
2613
2614                 if (!cmd->se_lun) {
2615                         pr_err("ITT: 0x%08x, [i,t]_state: %u/%u\n",
2616                                 cmd->se_tfo->get_task_tag(cmd),
2617                                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
2618                         BUG();
2619                 }
2620                 /*
2621                  * If the Storage engine still owns the iscsi_cmd_t, determine
2622                  * and/or stop its context.
2623                  */
2624                 pr_debug("SE_LUN[%d] - ITT: 0x%08x before transport"
2625                         "_lun_wait_for_tasks()\n", cmd->se_lun->unpacked_lun,
2626                         cmd->se_tfo->get_task_tag(cmd));
2627
2628                 if (transport_lun_wait_for_tasks(cmd, cmd->se_lun) < 0) {
2629                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2630                         continue;
2631                 }
2632
2633                 pr_debug("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
2634                         "_wait_for_tasks(): SUCCESS\n",
2635                         cmd->se_lun->unpacked_lun,
2636                         cmd->se_tfo->get_task_tag(cmd));
2637
2638                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
2639                 if (!(cmd->transport_state & CMD_T_DEV_ACTIVE)) {
2640                         spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2641                         goto check_cond;
2642                 }
2643                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
2644                 target_remove_from_state_list(cmd);
2645                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2646
2647                 /*
2648                  * The Storage engine stopped this struct se_cmd before it was
2649                  * send to the fabric frontend for delivery back to the
2650                  * Initiator Node.  Return this SCSI CDB back with an
2651                  * CHECK_CONDITION status.
2652                  */
2653 check_cond:
2654                 transport_send_check_condition_and_sense(cmd,
2655                                 TCM_NON_EXISTENT_LUN, 0);
2656                 /*
2657                  *  If the fabric frontend is waiting for this iscsi_cmd_t to
2658                  * be released, notify the waiting thread now that LU has
2659                  * finished accessing it.
2660                  */
2661                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
2662                 if (cmd->transport_state & CMD_T_LUN_FE_STOP) {
2663                         pr_debug("SE_LUN[%d] - Detected FE stop for"
2664                                 " struct se_cmd: %p ITT: 0x%08x\n",
2665                                 lun->unpacked_lun,
2666                                 cmd, cmd->se_tfo->get_task_tag(cmd));
2667
2668                         spin_unlock_irqrestore(&cmd->t_state_lock,
2669                                         cmd_flags);
2670                         transport_cmd_check_stop(cmd, false);
2671                         complete(&cmd->transport_lun_fe_stop_comp);
2672                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2673                         continue;
2674                 }
2675                 pr_debug("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
2676                         lun->unpacked_lun, cmd->se_tfo->get_task_tag(cmd));
2677
2678                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2679                 spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2680         }
2681         spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
2682 }
2683
2684 static int transport_clear_lun_thread(void *p)
2685 {
2686         struct se_lun *lun = p;
2687
2688         __transport_clear_lun_from_sessions(lun);
2689         complete(&lun->lun_shutdown_comp);
2690
2691         return 0;
2692 }
2693
2694 int transport_clear_lun_from_sessions(struct se_lun *lun)
2695 {
2696         struct task_struct *kt;
2697
2698         kt = kthread_run(transport_clear_lun_thread, lun,
2699                         "tcm_cl_%u", lun->unpacked_lun);
2700         if (IS_ERR(kt)) {
2701                 pr_err("Unable to start clear_lun thread\n");
2702                 return PTR_ERR(kt);
2703         }
2704         wait_for_completion(&lun->lun_shutdown_comp);
2705
2706         return 0;
2707 }
2708
2709 /**
2710  * transport_wait_for_tasks - wait for completion to occur
2711  * @cmd:        command to wait
2712  *
2713  * Called from frontend fabric context to wait for storage engine
2714  * to pause and/or release frontend generated struct se_cmd.
2715  */
2716 bool transport_wait_for_tasks(struct se_cmd *cmd)
2717 {
2718         unsigned long flags;
2719
2720         spin_lock_irqsave(&cmd->t_state_lock, flags);
2721         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
2722             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2723                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2724                 return false;
2725         }
2726
2727         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
2728             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2729                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2730                 return false;
2731         }
2732         /*
2733          * If we are already stopped due to an external event (ie: LUN shutdown)
2734          * sleep until the connection can have the passed struct se_cmd back.
2735          * The cmd->transport_lun_stopped_sem will be upped by
2736          * transport_clear_lun_from_sessions() once the ConfigFS context caller
2737          * has completed its operation on the struct se_cmd.
2738          */
2739         if (cmd->transport_state & CMD_T_LUN_STOP) {
2740                 pr_debug("wait_for_tasks: Stopping"
2741                         " wait_for_completion(&cmd->t_tasktransport_lun_fe"
2742                         "_stop_comp); for ITT: 0x%08x\n",
2743                         cmd->se_tfo->get_task_tag(cmd));
2744                 /*
2745                  * There is a special case for WRITES where a FE exception +
2746                  * LUN shutdown means ConfigFS context is still sleeping on
2747                  * transport_lun_stop_comp in transport_lun_wait_for_tasks().
2748                  * We go ahead and up transport_lun_stop_comp just to be sure
2749                  * here.
2750                  */
2751                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2752                 complete(&cmd->transport_lun_stop_comp);
2753                 wait_for_completion(&cmd->transport_lun_fe_stop_comp);
2754                 spin_lock_irqsave(&cmd->t_state_lock, flags);
2755
2756                 target_remove_from_state_list(cmd);
2757                 /*
2758                  * At this point, the frontend who was the originator of this
2759                  * struct se_cmd, now owns the structure and can be released through
2760                  * normal means below.
2761                  */
2762                 pr_debug("wait_for_tasks: Stopped"
2763                         " wait_for_completion(&cmd->t_tasktransport_lun_fe_"
2764                         "stop_comp); for ITT: 0x%08x\n",
2765                         cmd->se_tfo->get_task_tag(cmd));
2766
2767                 cmd->transport_state &= ~CMD_T_LUN_STOP;
2768         }
2769
2770         if (!(cmd->transport_state & CMD_T_ACTIVE)) {
2771                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2772                 return false;
2773         }
2774
2775         cmd->transport_state |= CMD_T_STOP;
2776
2777         pr_debug("wait_for_tasks: Stopping %p ITT: 0x%08x"
2778                 " i_state: %d, t_state: %d, CMD_T_STOP\n",
2779                 cmd, cmd->se_tfo->get_task_tag(cmd),
2780                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
2781
2782         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2783
2784         wait_for_completion(&cmd->t_transport_stop_comp);
2785
2786         spin_lock_irqsave(&cmd->t_state_lock, flags);
2787         cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
2788
2789         pr_debug("wait_for_tasks: Stopped wait_for_completion("
2790                 "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n",
2791                 cmd->se_tfo->get_task_tag(cmd));
2792
2793         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2794
2795         return true;
2796 }
2797 EXPORT_SYMBOL(transport_wait_for_tasks);
2798
2799 static int transport_get_sense_codes(
2800         struct se_cmd *cmd,
2801         u8 *asc,
2802         u8 *ascq)
2803 {
2804         *asc = cmd->scsi_asc;
2805         *ascq = cmd->scsi_ascq;
2806
2807         return 0;
2808 }
2809
2810 static int transport_set_sense_codes(
2811         struct se_cmd *cmd,
2812         u8 asc,
2813         u8 ascq)
2814 {
2815         cmd->scsi_asc = asc;
2816         cmd->scsi_ascq = ascq;
2817
2818         return 0;
2819 }
2820
2821 int transport_send_check_condition_and_sense(
2822         struct se_cmd *cmd,
2823         u8 reason,
2824         int from_transport)
2825 {
2826         unsigned char *buffer = cmd->sense_buffer;
2827         unsigned long flags;
2828         u8 asc = 0, ascq = 0;
2829
2830         spin_lock_irqsave(&cmd->t_state_lock, flags);
2831         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2832                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2833                 return 0;
2834         }
2835         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
2836         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2837
2838         if (!reason && from_transport)
2839                 goto after_reason;
2840
2841         if (!from_transport)
2842                 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
2843
2844         /*
2845          * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
2846          * SENSE KEY values from include/scsi/scsi.h
2847          */
2848         switch (reason) {
2849         case TCM_NON_EXISTENT_LUN:
2850                 /* CURRENT ERROR */
2851                 buffer[0] = 0x70;
2852                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2853                 /* ILLEGAL REQUEST */
2854                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2855                 /* LOGICAL UNIT NOT SUPPORTED */
2856                 buffer[SPC_ASC_KEY_OFFSET] = 0x25;
2857                 break;
2858         case TCM_UNSUPPORTED_SCSI_OPCODE:
2859         case TCM_SECTOR_COUNT_TOO_MANY:
2860                 /* CURRENT ERROR */
2861                 buffer[0] = 0x70;
2862                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2863                 /* ILLEGAL REQUEST */
2864                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2865                 /* INVALID COMMAND OPERATION CODE */
2866                 buffer[SPC_ASC_KEY_OFFSET] = 0x20;
2867                 break;
2868         case TCM_UNKNOWN_MODE_PAGE:
2869                 /* CURRENT ERROR */
2870                 buffer[0] = 0x70;
2871                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2872                 /* ILLEGAL REQUEST */
2873                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2874                 /* INVALID FIELD IN CDB */
2875                 buffer[SPC_ASC_KEY_OFFSET] = 0x24;
2876                 break;
2877         case TCM_CHECK_CONDITION_ABORT_CMD:
2878                 /* CURRENT ERROR */
2879                 buffer[0] = 0x70;
2880                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2881                 /* ABORTED COMMAND */
2882                 buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2883                 /* BUS DEVICE RESET FUNCTION OCCURRED */
2884                 buffer[SPC_ASC_KEY_OFFSET] = 0x29;
2885                 buffer[SPC_ASCQ_KEY_OFFSET] = 0x03;
2886                 break;
2887         case TCM_INCORRECT_AMOUNT_OF_DATA:
2888                 /* CURRENT ERROR */
2889                 buffer[0] = 0x70;
2890                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2891                 /* ABORTED COMMAND */
2892                 buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2893                 /* WRITE ERROR */
2894                 buffer[SPC_ASC_KEY_OFFSET] = 0x0c;
2895                 /* NOT ENOUGH UNSOLICITED DATA */
2896                 buffer[SPC_ASCQ_KEY_OFFSET] = 0x0d;
2897                 break;
2898         case TCM_INVALID_CDB_FIELD:
2899                 /* CURRENT ERROR */
2900                 buffer[0] = 0x70;
2901                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2902                 /* ILLEGAL REQUEST */
2903                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2904                 /* INVALID FIELD IN CDB */
2905                 buffer[SPC_ASC_KEY_OFFSET] = 0x24;
2906                 break;
2907         case TCM_INVALID_PARAMETER_LIST:
2908                 /* CURRENT ERROR */
2909                 buffer[0] = 0x70;
2910                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2911                 /* ILLEGAL REQUEST */
2912                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2913                 /* INVALID FIELD IN PARAMETER LIST */
2914                 buffer[SPC_ASC_KEY_OFFSET] = 0x26;
2915                 break;
2916         case TCM_UNEXPECTED_UNSOLICITED_DATA:
2917                 /* CURRENT ERROR */
2918                 buffer[0] = 0x70;
2919                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2920                 /* ABORTED COMMAND */
2921                 buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2922                 /* WRITE ERROR */
2923                 buffer[SPC_ASC_KEY_OFFSET] = 0x0c;
2924                 /* UNEXPECTED_UNSOLICITED_DATA */
2925                 buffer[SPC_ASCQ_KEY_OFFSET] = 0x0c;
2926                 break;
2927         case TCM_SERVICE_CRC_ERROR:
2928                 /* CURRENT ERROR */
2929                 buffer[0] = 0x70;
2930                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2931                 /* ABORTED COMMAND */
2932                 buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2933                 /* PROTOCOL SERVICE CRC ERROR */
2934                 buffer[SPC_ASC_KEY_OFFSET] = 0x47;
2935                 /* N/A */
2936                 buffer[SPC_ASCQ_KEY_OFFSET] = 0x05;
2937                 break;
2938         case TCM_SNACK_REJECTED:
2939                 /* CURRENT ERROR */
2940                 buffer[0] = 0x70;
2941                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2942                 /* ABORTED COMMAND */
2943                 buffer[SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2944                 /* READ ERROR */
2945                 buffer[SPC_ASC_KEY_OFFSET] = 0x11;
2946                 /* FAILED RETRANSMISSION REQUEST */
2947                 buffer[SPC_ASCQ_KEY_OFFSET] = 0x13;
2948                 break;
2949         case TCM_WRITE_PROTECTED:
2950                 /* CURRENT ERROR */
2951                 buffer[0] = 0x70;
2952                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2953                 /* DATA PROTECT */
2954                 buffer[SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
2955                 /* WRITE PROTECTED */
2956                 buffer[SPC_ASC_KEY_OFFSET] = 0x27;
2957                 break;
2958         case TCM_ADDRESS_OUT_OF_RANGE:
2959                 /* CURRENT ERROR */
2960                 buffer[0] = 0x70;
2961                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2962                 /* ILLEGAL REQUEST */
2963                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2964                 /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
2965                 buffer[SPC_ASC_KEY_OFFSET] = 0x21;
2966                 break;
2967         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
2968                 /* CURRENT ERROR */
2969                 buffer[0] = 0x70;
2970                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2971                 /* UNIT ATTENTION */
2972                 buffer[SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
2973                 core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
2974                 buffer[SPC_ASC_KEY_OFFSET] = asc;
2975                 buffer[SPC_ASCQ_KEY_OFFSET] = ascq;
2976                 break;
2977         case TCM_CHECK_CONDITION_NOT_READY:
2978                 /* CURRENT ERROR */
2979                 buffer[0] = 0x70;
2980                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2981                 /* Not Ready */
2982                 buffer[SPC_SENSE_KEY_OFFSET] = NOT_READY;
2983                 transport_get_sense_codes(cmd, &asc, &ascq);
2984                 buffer[SPC_ASC_KEY_OFFSET] = asc;
2985                 buffer[SPC_ASCQ_KEY_OFFSET] = ascq;
2986                 break;
2987         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
2988         default:
2989                 /* CURRENT ERROR */
2990                 buffer[0] = 0x70;
2991                 buffer[SPC_ADD_SENSE_LEN_OFFSET] = 10;
2992                 /* ILLEGAL REQUEST */
2993                 buffer[SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2994                 /* LOGICAL UNIT COMMUNICATION FAILURE */
2995                 buffer[SPC_ASC_KEY_OFFSET] = 0x80;
2996                 break;
2997         }
2998         /*
2999          * This code uses linux/include/scsi/scsi.h SAM status codes!
3000          */
3001         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3002         /*
3003          * Automatically padded, this value is encoded in the fabric's
3004          * data_length response PDU containing the SCSI defined sense data.
3005          */
3006         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER;
3007
3008 after_reason:
3009         return cmd->se_tfo->queue_status(cmd);
3010 }
3011 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3012
3013 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3014 {
3015         int ret = 0;
3016
3017         if (cmd->transport_state & CMD_T_ABORTED) {
3018                 if (!send_status ||
3019                      (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
3020                         return 1;
3021
3022                 pr_debug("Sending delayed SAM_STAT_TASK_ABORTED"
3023                         " status for CDB: 0x%02x ITT: 0x%08x\n",
3024                         cmd->t_task_cdb[0],
3025                         cmd->se_tfo->get_task_tag(cmd));
3026
3027                 cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
3028                 cmd->se_tfo->queue_status(cmd);
3029                 ret = 1;
3030         }
3031         return ret;
3032 }
3033 EXPORT_SYMBOL(transport_check_aborted_status);
3034
3035 void transport_send_task_abort(struct se_cmd *cmd)
3036 {
3037         unsigned long flags;
3038
3039         spin_lock_irqsave(&cmd->t_state_lock, flags);
3040         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3041                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3042                 return;
3043         }
3044         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3045
3046         /*
3047          * If there are still expected incoming fabric WRITEs, we wait
3048          * until until they have completed before sending a TASK_ABORTED
3049          * response.  This response with TASK_ABORTED status will be
3050          * queued back to fabric module by transport_check_aborted_status().
3051          */
3052         if (cmd->data_direction == DMA_TO_DEVICE) {
3053                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
3054                         cmd->transport_state |= CMD_T_ABORTED;
3055                         smp_mb__after_atomic_inc();
3056                 }
3057         }
3058         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3059
3060         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
3061                 " ITT: 0x%08x\n", cmd->t_task_cdb[0],
3062                 cmd->se_tfo->get_task_tag(cmd));
3063
3064         cmd->se_tfo->queue_status(cmd);
3065 }
3066
3067 static void target_tmr_work(struct work_struct *work)
3068 {
3069         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3070         struct se_device *dev = cmd->se_dev;
3071         struct se_tmr_req *tmr = cmd->se_tmr_req;
3072         int ret;
3073
3074         switch (tmr->function) {
3075         case TMR_ABORT_TASK:
3076                 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3077                 break;
3078         case TMR_ABORT_TASK_SET:
3079         case TMR_CLEAR_ACA:
3080         case TMR_CLEAR_TASK_SET:
3081                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3082                 break;
3083         case TMR_LUN_RESET:
3084                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3085                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3086                                          TMR_FUNCTION_REJECTED;
3087                 break;
3088         case TMR_TARGET_WARM_RESET:
3089                 tmr->response = TMR_FUNCTION_REJECTED;
3090                 break;
3091         case TMR_TARGET_COLD_RESET:
3092                 tmr->response = TMR_FUNCTION_REJECTED;
3093                 break;
3094         default:
3095                 pr_err("Uknown TMR function: 0x%02x.\n",
3096                                 tmr->function);
3097                 tmr->response = TMR_FUNCTION_REJECTED;
3098                 break;
3099         }
3100
3101         cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3102         cmd->se_tfo->queue_tm_rsp(cmd);
3103
3104         transport_cmd_check_stop_to_fabric(cmd);
3105 }
3106
3107 int transport_generic_handle_tmr(
3108         struct se_cmd *cmd)
3109 {
3110         INIT_WORK(&cmd->work, target_tmr_work);
3111         queue_work(cmd->se_dev->tmr_wq, &cmd->work);
3112         return 0;
3113 }
3114 EXPORT_SYMBOL(transport_generic_handle_tmr);