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