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