scsi: target: Fix handling of removed LUNs
[linux-2.6-microblaze.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-2013 Datera, Inc.
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/spinlock.h>
32 #include <linux/kthread.h>
33 #include <linux/in.h>
34 #include <linux/cdrom.h>
35 #include <linux/module.h>
36 #include <linux/ratelimit.h>
37 #include <linux/vmalloc.h>
38 #include <asm/unaligned.h>
39 #include <net/sock.h>
40 #include <net/tcp.h>
41 #include <scsi/scsi_proto.h>
42 #include <scsi/scsi_common.h>
43
44 #include <target/target_core_base.h>
45 #include <target/target_core_backend.h>
46 #include <target/target_core_fabric.h>
47
48 #include "target_core_internal.h"
49 #include "target_core_alua.h"
50 #include "target_core_pr.h"
51 #include "target_core_ua.h"
52
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/target.h>
55
56 static struct workqueue_struct *target_completion_wq;
57 static struct kmem_cache *se_sess_cache;
58 struct kmem_cache *se_ua_cache;
59 struct kmem_cache *t10_pr_reg_cache;
60 struct kmem_cache *t10_alua_lu_gp_cache;
61 struct kmem_cache *t10_alua_lu_gp_mem_cache;
62 struct kmem_cache *t10_alua_tg_pt_gp_cache;
63 struct kmem_cache *t10_alua_lba_map_cache;
64 struct kmem_cache *t10_alua_lba_map_mem_cache;
65
66 static void transport_complete_task_attr(struct se_cmd *cmd);
67 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
68 static void transport_handle_queue_full(struct se_cmd *cmd,
69                 struct se_device *dev, int err, bool write_pending);
70 static void target_complete_ok_work(struct work_struct *work);
71
72 int init_se_kmem_caches(void)
73 {
74         se_sess_cache = kmem_cache_create("se_sess_cache",
75                         sizeof(struct se_session), __alignof__(struct se_session),
76                         0, NULL);
77         if (!se_sess_cache) {
78                 pr_err("kmem_cache_create() for struct se_session"
79                                 " failed\n");
80                 goto out;
81         }
82         se_ua_cache = kmem_cache_create("se_ua_cache",
83                         sizeof(struct se_ua), __alignof__(struct se_ua),
84                         0, NULL);
85         if (!se_ua_cache) {
86                 pr_err("kmem_cache_create() for struct se_ua failed\n");
87                 goto out_free_sess_cache;
88         }
89         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
90                         sizeof(struct t10_pr_registration),
91                         __alignof__(struct t10_pr_registration), 0, NULL);
92         if (!t10_pr_reg_cache) {
93                 pr_err("kmem_cache_create() for struct t10_pr_registration"
94                                 " failed\n");
95                 goto out_free_ua_cache;
96         }
97         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
98                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
99                         0, NULL);
100         if (!t10_alua_lu_gp_cache) {
101                 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
102                                 " failed\n");
103                 goto out_free_pr_reg_cache;
104         }
105         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
106                         sizeof(struct t10_alua_lu_gp_member),
107                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
108         if (!t10_alua_lu_gp_mem_cache) {
109                 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
110                                 "cache failed\n");
111                 goto out_free_lu_gp_cache;
112         }
113         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
114                         sizeof(struct t10_alua_tg_pt_gp),
115                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
116         if (!t10_alua_tg_pt_gp_cache) {
117                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
118                                 "cache failed\n");
119                 goto out_free_lu_gp_mem_cache;
120         }
121         t10_alua_lba_map_cache = kmem_cache_create(
122                         "t10_alua_lba_map_cache",
123                         sizeof(struct t10_alua_lba_map),
124                         __alignof__(struct t10_alua_lba_map), 0, NULL);
125         if (!t10_alua_lba_map_cache) {
126                 pr_err("kmem_cache_create() for t10_alua_lba_map_"
127                                 "cache failed\n");
128                 goto out_free_tg_pt_gp_cache;
129         }
130         t10_alua_lba_map_mem_cache = kmem_cache_create(
131                         "t10_alua_lba_map_mem_cache",
132                         sizeof(struct t10_alua_lba_map_member),
133                         __alignof__(struct t10_alua_lba_map_member), 0, NULL);
134         if (!t10_alua_lba_map_mem_cache) {
135                 pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
136                                 "cache failed\n");
137                 goto out_free_lba_map_cache;
138         }
139
140         target_completion_wq = alloc_workqueue("target_completion",
141                                                WQ_MEM_RECLAIM, 0);
142         if (!target_completion_wq)
143                 goto out_free_lba_map_mem_cache;
144
145         return 0;
146
147 out_free_lba_map_mem_cache:
148         kmem_cache_destroy(t10_alua_lba_map_mem_cache);
149 out_free_lba_map_cache:
150         kmem_cache_destroy(t10_alua_lba_map_cache);
151 out_free_tg_pt_gp_cache:
152         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
153 out_free_lu_gp_mem_cache:
154         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
155 out_free_lu_gp_cache:
156         kmem_cache_destroy(t10_alua_lu_gp_cache);
157 out_free_pr_reg_cache:
158         kmem_cache_destroy(t10_pr_reg_cache);
159 out_free_ua_cache:
160         kmem_cache_destroy(se_ua_cache);
161 out_free_sess_cache:
162         kmem_cache_destroy(se_sess_cache);
163 out:
164         return -ENOMEM;
165 }
166
167 void release_se_kmem_caches(void)
168 {
169         destroy_workqueue(target_completion_wq);
170         kmem_cache_destroy(se_sess_cache);
171         kmem_cache_destroy(se_ua_cache);
172         kmem_cache_destroy(t10_pr_reg_cache);
173         kmem_cache_destroy(t10_alua_lu_gp_cache);
174         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
175         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
176         kmem_cache_destroy(t10_alua_lba_map_cache);
177         kmem_cache_destroy(t10_alua_lba_map_mem_cache);
178 }
179
180 /* This code ensures unique mib indexes are handed out. */
181 static DEFINE_SPINLOCK(scsi_mib_index_lock);
182 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
183
184 /*
185  * Allocate a new row index for the entry type specified
186  */
187 u32 scsi_get_new_index(scsi_index_t type)
188 {
189         u32 new_index;
190
191         BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
192
193         spin_lock(&scsi_mib_index_lock);
194         new_index = ++scsi_mib_index[type];
195         spin_unlock(&scsi_mib_index_lock);
196
197         return new_index;
198 }
199
200 void transport_subsystem_check_init(void)
201 {
202         int ret;
203         static int sub_api_initialized;
204
205         if (sub_api_initialized)
206                 return;
207
208         ret = request_module("target_core_iblock");
209         if (ret != 0)
210                 pr_err("Unable to load target_core_iblock\n");
211
212         ret = request_module("target_core_file");
213         if (ret != 0)
214                 pr_err("Unable to load target_core_file\n");
215
216         ret = request_module("target_core_pscsi");
217         if (ret != 0)
218                 pr_err("Unable to load target_core_pscsi\n");
219
220         ret = request_module("target_core_user");
221         if (ret != 0)
222                 pr_err("Unable to load target_core_user\n");
223
224         sub_api_initialized = 1;
225 }
226
227 /**
228  * transport_init_session - initialize a session object
229  * @se_sess: Session object pointer.
230  *
231  * The caller must have zero-initialized @se_sess before calling this function.
232  */
233 void transport_init_session(struct se_session *se_sess)
234 {
235         INIT_LIST_HEAD(&se_sess->sess_list);
236         INIT_LIST_HEAD(&se_sess->sess_acl_list);
237         INIT_LIST_HEAD(&se_sess->sess_cmd_list);
238         spin_lock_init(&se_sess->sess_cmd_lock);
239         init_waitqueue_head(&se_sess->cmd_list_wq);
240 }
241 EXPORT_SYMBOL(transport_init_session);
242
243 /**
244  * transport_alloc_session - allocate a session object and initialize it
245  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
246  */
247 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
248 {
249         struct se_session *se_sess;
250
251         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
252         if (!se_sess) {
253                 pr_err("Unable to allocate struct se_session from"
254                                 " se_sess_cache\n");
255                 return ERR_PTR(-ENOMEM);
256         }
257         transport_init_session(se_sess);
258         se_sess->sup_prot_ops = sup_prot_ops;
259
260         return se_sess;
261 }
262 EXPORT_SYMBOL(transport_alloc_session);
263
264 /**
265  * transport_alloc_session_tags - allocate target driver private data
266  * @se_sess:  Session pointer.
267  * @tag_num:  Maximum number of in-flight commands between initiator and target.
268  * @tag_size: Size in bytes of the private data a target driver associates with
269  *            each command.
270  */
271 int transport_alloc_session_tags(struct se_session *se_sess,
272                                  unsigned int tag_num, unsigned int tag_size)
273 {
274         int rc;
275
276         se_sess->sess_cmd_map = kcalloc(tag_size, tag_num,
277                                         GFP_KERNEL | __GFP_NOWARN | __GFP_RETRY_MAYFAIL);
278         if (!se_sess->sess_cmd_map) {
279                 se_sess->sess_cmd_map = vzalloc(array_size(tag_size, tag_num));
280                 if (!se_sess->sess_cmd_map) {
281                         pr_err("Unable to allocate se_sess->sess_cmd_map\n");
282                         return -ENOMEM;
283                 }
284         }
285
286         rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
287                         false, GFP_KERNEL, NUMA_NO_NODE);
288         if (rc < 0) {
289                 pr_err("Unable to init se_sess->sess_tag_pool,"
290                         " tag_num: %u\n", tag_num);
291                 kvfree(se_sess->sess_cmd_map);
292                 se_sess->sess_cmd_map = NULL;
293                 return -ENOMEM;
294         }
295
296         return 0;
297 }
298 EXPORT_SYMBOL(transport_alloc_session_tags);
299
300 /**
301  * transport_init_session_tags - allocate a session and target driver private data
302  * @tag_num:  Maximum number of in-flight commands between initiator and target.
303  * @tag_size: Size in bytes of the private data a target driver associates with
304  *            each command.
305  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
306  */
307 struct se_session *transport_init_session_tags(unsigned int tag_num,
308                                                unsigned int tag_size,
309                                                enum target_prot_op sup_prot_ops)
310 {
311         struct se_session *se_sess;
312         int rc;
313
314         if (tag_num != 0 && !tag_size) {
315                 pr_err("init_session_tags called with percpu-ida tag_num:"
316                        " %u, but zero tag_size\n", tag_num);
317                 return ERR_PTR(-EINVAL);
318         }
319         if (!tag_num && tag_size) {
320                 pr_err("init_session_tags called with percpu-ida tag_size:"
321                        " %u, but zero tag_num\n", tag_size);
322                 return ERR_PTR(-EINVAL);
323         }
324
325         se_sess = transport_alloc_session(sup_prot_ops);
326         if (IS_ERR(se_sess))
327                 return se_sess;
328
329         rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
330         if (rc < 0) {
331                 transport_free_session(se_sess);
332                 return ERR_PTR(-ENOMEM);
333         }
334
335         return se_sess;
336 }
337 EXPORT_SYMBOL(transport_init_session_tags);
338
339 /*
340  * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
341  */
342 void __transport_register_session(
343         struct se_portal_group *se_tpg,
344         struct se_node_acl *se_nacl,
345         struct se_session *se_sess,
346         void *fabric_sess_ptr)
347 {
348         const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
349         unsigned char buf[PR_REG_ISID_LEN];
350
351         se_sess->se_tpg = se_tpg;
352         se_sess->fabric_sess_ptr = fabric_sess_ptr;
353         /*
354          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
355          *
356          * Only set for struct se_session's that will actually be moving I/O.
357          * eg: *NOT* discovery sessions.
358          */
359         if (se_nacl) {
360                 /*
361                  *
362                  * Determine if fabric allows for T10-PI feature bits exposed to
363                  * initiators for device backends with !dev->dev_attrib.pi_prot_type.
364                  *
365                  * If so, then always save prot_type on a per se_node_acl node
366                  * basis and re-instate the previous sess_prot_type to avoid
367                  * disabling PI from below any previously initiator side
368                  * registered LUNs.
369                  */
370                 if (se_nacl->saved_prot_type)
371                         se_sess->sess_prot_type = se_nacl->saved_prot_type;
372                 else if (tfo->tpg_check_prot_fabric_only)
373                         se_sess->sess_prot_type = se_nacl->saved_prot_type =
374                                         tfo->tpg_check_prot_fabric_only(se_tpg);
375                 /*
376                  * If the fabric module supports an ISID based TransportID,
377                  * save this value in binary from the fabric I_T Nexus now.
378                  */
379                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
380                         memset(&buf[0], 0, PR_REG_ISID_LEN);
381                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
382                                         &buf[0], PR_REG_ISID_LEN);
383                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
384                 }
385
386                 spin_lock_irq(&se_nacl->nacl_sess_lock);
387                 /*
388                  * The se_nacl->nacl_sess pointer will be set to the
389                  * last active I_T Nexus for each struct se_node_acl.
390                  */
391                 se_nacl->nacl_sess = se_sess;
392
393                 list_add_tail(&se_sess->sess_acl_list,
394                               &se_nacl->acl_sess_list);
395                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
396         }
397         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
398
399         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
400                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
401 }
402 EXPORT_SYMBOL(__transport_register_session);
403
404 void transport_register_session(
405         struct se_portal_group *se_tpg,
406         struct se_node_acl *se_nacl,
407         struct se_session *se_sess,
408         void *fabric_sess_ptr)
409 {
410         unsigned long flags;
411
412         spin_lock_irqsave(&se_tpg->session_lock, flags);
413         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
414         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
415 }
416 EXPORT_SYMBOL(transport_register_session);
417
418 struct se_session *
419 target_alloc_session(struct se_portal_group *tpg,
420                      unsigned int tag_num, unsigned int tag_size,
421                      enum target_prot_op prot_op,
422                      const char *initiatorname, void *private,
423                      int (*callback)(struct se_portal_group *,
424                                      struct se_session *, void *))
425 {
426         struct se_session *sess;
427
428         /*
429          * If the fabric driver is using percpu-ida based pre allocation
430          * of I/O descriptor tags, go ahead and perform that setup now..
431          */
432         if (tag_num != 0)
433                 sess = transport_init_session_tags(tag_num, tag_size, prot_op);
434         else
435                 sess = transport_alloc_session(prot_op);
436
437         if (IS_ERR(sess))
438                 return sess;
439
440         sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
441                                         (unsigned char *)initiatorname);
442         if (!sess->se_node_acl) {
443                 transport_free_session(sess);
444                 return ERR_PTR(-EACCES);
445         }
446         /*
447          * Go ahead and perform any remaining fabric setup that is
448          * required before transport_register_session().
449          */
450         if (callback != NULL) {
451                 int rc = callback(tpg, sess, private);
452                 if (rc) {
453                         transport_free_session(sess);
454                         return ERR_PTR(rc);
455                 }
456         }
457
458         transport_register_session(tpg, sess->se_node_acl, sess, private);
459         return sess;
460 }
461 EXPORT_SYMBOL(target_alloc_session);
462
463 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
464 {
465         struct se_session *se_sess;
466         ssize_t len = 0;
467
468         spin_lock_bh(&se_tpg->session_lock);
469         list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
470                 if (!se_sess->se_node_acl)
471                         continue;
472                 if (!se_sess->se_node_acl->dynamic_node_acl)
473                         continue;
474                 if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
475                         break;
476
477                 len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
478                                 se_sess->se_node_acl->initiatorname);
479                 len += 1; /* Include NULL terminator */
480         }
481         spin_unlock_bh(&se_tpg->session_lock);
482
483         return len;
484 }
485 EXPORT_SYMBOL(target_show_dynamic_sessions);
486
487 static void target_complete_nacl(struct kref *kref)
488 {
489         struct se_node_acl *nacl = container_of(kref,
490                                 struct se_node_acl, acl_kref);
491         struct se_portal_group *se_tpg = nacl->se_tpg;
492
493         if (!nacl->dynamic_stop) {
494                 complete(&nacl->acl_free_comp);
495                 return;
496         }
497
498         mutex_lock(&se_tpg->acl_node_mutex);
499         list_del_init(&nacl->acl_list);
500         mutex_unlock(&se_tpg->acl_node_mutex);
501
502         core_tpg_wait_for_nacl_pr_ref(nacl);
503         core_free_device_list_for_node(nacl, se_tpg);
504         kfree(nacl);
505 }
506
507 void target_put_nacl(struct se_node_acl *nacl)
508 {
509         kref_put(&nacl->acl_kref, target_complete_nacl);
510 }
511 EXPORT_SYMBOL(target_put_nacl);
512
513 void transport_deregister_session_configfs(struct se_session *se_sess)
514 {
515         struct se_node_acl *se_nacl;
516         unsigned long flags;
517         /*
518          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
519          */
520         se_nacl = se_sess->se_node_acl;
521         if (se_nacl) {
522                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
523                 if (!list_empty(&se_sess->sess_acl_list))
524                         list_del_init(&se_sess->sess_acl_list);
525                 /*
526                  * If the session list is empty, then clear the pointer.
527                  * Otherwise, set the struct se_session pointer from the tail
528                  * element of the per struct se_node_acl active session list.
529                  */
530                 if (list_empty(&se_nacl->acl_sess_list))
531                         se_nacl->nacl_sess = NULL;
532                 else {
533                         se_nacl->nacl_sess = container_of(
534                                         se_nacl->acl_sess_list.prev,
535                                         struct se_session, sess_acl_list);
536                 }
537                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
538         }
539 }
540 EXPORT_SYMBOL(transport_deregister_session_configfs);
541
542 void transport_free_session(struct se_session *se_sess)
543 {
544         struct se_node_acl *se_nacl = se_sess->se_node_acl;
545
546         /*
547          * Drop the se_node_acl->nacl_kref obtained from within
548          * core_tpg_get_initiator_node_acl().
549          */
550         if (se_nacl) {
551                 struct se_portal_group *se_tpg = se_nacl->se_tpg;
552                 const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
553                 unsigned long flags;
554
555                 se_sess->se_node_acl = NULL;
556
557                 /*
558                  * Also determine if we need to drop the extra ->cmd_kref if
559                  * it had been previously dynamically generated, and
560                  * the endpoint is not caching dynamic ACLs.
561                  */
562                 mutex_lock(&se_tpg->acl_node_mutex);
563                 if (se_nacl->dynamic_node_acl &&
564                     !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
565                         spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
566                         if (list_empty(&se_nacl->acl_sess_list))
567                                 se_nacl->dynamic_stop = true;
568                         spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
569
570                         if (se_nacl->dynamic_stop)
571                                 list_del_init(&se_nacl->acl_list);
572                 }
573                 mutex_unlock(&se_tpg->acl_node_mutex);
574
575                 if (se_nacl->dynamic_stop)
576                         target_put_nacl(se_nacl);
577
578                 target_put_nacl(se_nacl);
579         }
580         if (se_sess->sess_cmd_map) {
581                 sbitmap_queue_free(&se_sess->sess_tag_pool);
582                 kvfree(se_sess->sess_cmd_map);
583         }
584         kmem_cache_free(se_sess_cache, se_sess);
585 }
586 EXPORT_SYMBOL(transport_free_session);
587
588 void transport_deregister_session(struct se_session *se_sess)
589 {
590         struct se_portal_group *se_tpg = se_sess->se_tpg;
591         unsigned long flags;
592
593         if (!se_tpg) {
594                 transport_free_session(se_sess);
595                 return;
596         }
597
598         spin_lock_irqsave(&se_tpg->session_lock, flags);
599         list_del(&se_sess->sess_list);
600         se_sess->se_tpg = NULL;
601         se_sess->fabric_sess_ptr = NULL;
602         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
603
604         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
605                 se_tpg->se_tpg_tfo->get_fabric_name());
606         /*
607          * If last kref is dropping now for an explicit NodeACL, awake sleeping
608          * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
609          * removal context from within transport_free_session() code.
610          *
611          * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
612          * to release all remaining generate_node_acl=1 created ACL resources.
613          */
614
615         transport_free_session(se_sess);
616 }
617 EXPORT_SYMBOL(transport_deregister_session);
618
619 static void target_remove_from_state_list(struct se_cmd *cmd)
620 {
621         struct se_device *dev = cmd->se_dev;
622         unsigned long flags;
623
624         if (!dev)
625                 return;
626
627         spin_lock_irqsave(&dev->execute_task_lock, flags);
628         if (cmd->state_active) {
629                 list_del(&cmd->state_list);
630                 cmd->state_active = false;
631         }
632         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
633 }
634
635 /*
636  * This function is called by the target core after the target core has
637  * finished processing a SCSI command or SCSI TMF. Both the regular command
638  * processing code and the code for aborting commands can call this
639  * function. CMD_T_STOP is set if and only if another thread is waiting
640  * inside transport_wait_for_tasks() for t_transport_stop_comp.
641  */
642 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
643 {
644         unsigned long flags;
645
646         target_remove_from_state_list(cmd);
647
648         /*
649          * Clear struct se_cmd->se_lun before the handoff to FE.
650          */
651         cmd->se_lun = NULL;
652
653         spin_lock_irqsave(&cmd->t_state_lock, flags);
654         /*
655          * Determine if frontend context caller is requesting the stopping of
656          * this command for frontend exceptions.
657          */
658         if (cmd->transport_state & CMD_T_STOP) {
659                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
660                         __func__, __LINE__, cmd->tag);
661
662                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
663
664                 complete_all(&cmd->t_transport_stop_comp);
665                 return 1;
666         }
667         cmd->transport_state &= ~CMD_T_ACTIVE;
668         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
669
670         /*
671          * Some fabric modules like tcm_loop can release their internally
672          * allocated I/O reference and struct se_cmd now.
673          *
674          * Fabric modules are expected to return '1' here if the se_cmd being
675          * passed is released at this point, or zero if not being released.
676          */
677         return cmd->se_tfo->check_stop_free(cmd);
678 }
679
680 static void transport_lun_remove_cmd(struct se_cmd *cmd)
681 {
682         struct se_lun *lun = cmd->se_lun;
683
684         if (!lun)
685                 return;
686
687         if (cmpxchg(&cmd->lun_ref_active, true, false))
688                 percpu_ref_put(&lun->lun_ref);
689 }
690
691 int transport_cmd_finish_abort(struct se_cmd *cmd)
692 {
693         bool send_tas = cmd->transport_state & CMD_T_TAS;
694         bool ack_kref = (cmd->se_cmd_flags & SCF_ACK_KREF);
695         int ret = 0;
696
697         if (send_tas)
698                 transport_send_task_abort(cmd);
699
700         if (cmd->se_cmd_flags & SCF_SE_LUN_CMD)
701                 transport_lun_remove_cmd(cmd);
702         /*
703          * Allow the fabric driver to unmap any resources before
704          * releasing the descriptor via TFO->release_cmd()
705          */
706         if (!send_tas)
707                 cmd->se_tfo->aborted_task(cmd);
708
709         if (transport_cmd_check_stop_to_fabric(cmd))
710                 return 1;
711         if (!send_tas && ack_kref)
712                 ret = target_put_sess_cmd(cmd);
713
714         return ret;
715 }
716
717 static void target_complete_failure_work(struct work_struct *work)
718 {
719         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
720
721         transport_generic_request_failure(cmd,
722                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
723 }
724
725 /*
726  * Used when asking transport to copy Sense Data from the underlying
727  * Linux/SCSI struct scsi_cmnd
728  */
729 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
730 {
731         struct se_device *dev = cmd->se_dev;
732
733         WARN_ON(!cmd->se_lun);
734
735         if (!dev)
736                 return NULL;
737
738         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
739                 return NULL;
740
741         cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
742
743         pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
744                 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
745         return cmd->sense_buffer;
746 }
747
748 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
749 {
750         unsigned char *cmd_sense_buf;
751         unsigned long flags;
752
753         spin_lock_irqsave(&cmd->t_state_lock, flags);
754         cmd_sense_buf = transport_get_sense_buffer(cmd);
755         if (!cmd_sense_buf) {
756                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
757                 return;
758         }
759
760         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
761         memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
762         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
763 }
764 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
765
766 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
767 {
768         struct se_device *dev = cmd->se_dev;
769         int success;
770         unsigned long flags;
771
772         cmd->scsi_status = scsi_status;
773
774         spin_lock_irqsave(&cmd->t_state_lock, flags);
775         switch (cmd->scsi_status) {
776         case SAM_STAT_CHECK_CONDITION:
777                 if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
778                         success = 1;
779                 else
780                         success = 0;
781                 break;
782         default:
783                 success = 1;
784                 break;
785         }
786
787         /*
788          * Check for case where an explicit ABORT_TASK has been received
789          * and transport_wait_for_tasks() will be waiting for completion..
790          */
791         if (cmd->transport_state & CMD_T_ABORTED ||
792             cmd->transport_state & CMD_T_STOP) {
793                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
794                 /*
795                  * If COMPARE_AND_WRITE was stopped by __transport_wait_for_tasks(),
796                  * release se_device->caw_sem obtained by sbc_compare_and_write()
797                  * since target_complete_ok_work() or target_complete_failure_work()
798                  * won't be called to invoke the normal CAW completion callbacks.
799                  */
800                 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
801                         up(&dev->caw_sem);
802                 }
803                 complete_all(&cmd->t_transport_stop_comp);
804                 return;
805         } else if (!success) {
806                 INIT_WORK(&cmd->work, target_complete_failure_work);
807         } else {
808                 INIT_WORK(&cmd->work, target_complete_ok_work);
809         }
810
811         cmd->t_state = TRANSPORT_COMPLETE;
812         cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
813         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
814
815         if (cmd->se_cmd_flags & SCF_USE_CPUID)
816                 queue_work_on(cmd->cpuid, target_completion_wq, &cmd->work);
817         else
818                 queue_work(target_completion_wq, &cmd->work);
819 }
820 EXPORT_SYMBOL(target_complete_cmd);
821
822 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
823 {
824         if ((scsi_status == SAM_STAT_GOOD ||
825              cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
826             length < cmd->data_length) {
827                 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
828                         cmd->residual_count += cmd->data_length - length;
829                 } else {
830                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
831                         cmd->residual_count = cmd->data_length - length;
832                 }
833
834                 cmd->data_length = length;
835         }
836
837         target_complete_cmd(cmd, scsi_status);
838 }
839 EXPORT_SYMBOL(target_complete_cmd_with_length);
840
841 static void target_add_to_state_list(struct se_cmd *cmd)
842 {
843         struct se_device *dev = cmd->se_dev;
844         unsigned long flags;
845
846         spin_lock_irqsave(&dev->execute_task_lock, flags);
847         if (!cmd->state_active) {
848                 list_add_tail(&cmd->state_list, &dev->state_list);
849                 cmd->state_active = true;
850         }
851         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
852 }
853
854 /*
855  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
856  */
857 static void transport_write_pending_qf(struct se_cmd *cmd);
858 static void transport_complete_qf(struct se_cmd *cmd);
859
860 void target_qf_do_work(struct work_struct *work)
861 {
862         struct se_device *dev = container_of(work, struct se_device,
863                                         qf_work_queue);
864         LIST_HEAD(qf_cmd_list);
865         struct se_cmd *cmd, *cmd_tmp;
866
867         spin_lock_irq(&dev->qf_cmd_lock);
868         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
869         spin_unlock_irq(&dev->qf_cmd_lock);
870
871         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
872                 list_del(&cmd->se_qf_node);
873                 atomic_dec_mb(&dev->dev_qf_count);
874
875                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
876                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
877                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
878                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
879                         : "UNKNOWN");
880
881                 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
882                         transport_write_pending_qf(cmd);
883                 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
884                          cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
885                         transport_complete_qf(cmd);
886         }
887 }
888
889 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
890 {
891         switch (cmd->data_direction) {
892         case DMA_NONE:
893                 return "NONE";
894         case DMA_FROM_DEVICE:
895                 return "READ";
896         case DMA_TO_DEVICE:
897                 return "WRITE";
898         case DMA_BIDIRECTIONAL:
899                 return "BIDI";
900         default:
901                 break;
902         }
903
904         return "UNKNOWN";
905 }
906
907 void transport_dump_dev_state(
908         struct se_device *dev,
909         char *b,
910         int *bl)
911 {
912         *bl += sprintf(b + *bl, "Status: ");
913         if (dev->export_count)
914                 *bl += sprintf(b + *bl, "ACTIVATED");
915         else
916                 *bl += sprintf(b + *bl, "DEACTIVATED");
917
918         *bl += sprintf(b + *bl, "  Max Queue Depth: %d", dev->queue_depth);
919         *bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
920                 dev->dev_attrib.block_size,
921                 dev->dev_attrib.hw_max_sectors);
922         *bl += sprintf(b + *bl, "        ");
923 }
924
925 void transport_dump_vpd_proto_id(
926         struct t10_vpd *vpd,
927         unsigned char *p_buf,
928         int p_buf_len)
929 {
930         unsigned char buf[VPD_TMP_BUF_SIZE];
931         int len;
932
933         memset(buf, 0, VPD_TMP_BUF_SIZE);
934         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
935
936         switch (vpd->protocol_identifier) {
937         case 0x00:
938                 sprintf(buf+len, "Fibre Channel\n");
939                 break;
940         case 0x10:
941                 sprintf(buf+len, "Parallel SCSI\n");
942                 break;
943         case 0x20:
944                 sprintf(buf+len, "SSA\n");
945                 break;
946         case 0x30:
947                 sprintf(buf+len, "IEEE 1394\n");
948                 break;
949         case 0x40:
950                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
951                                 " Protocol\n");
952                 break;
953         case 0x50:
954                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
955                 break;
956         case 0x60:
957                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
958                 break;
959         case 0x70:
960                 sprintf(buf+len, "Automation/Drive Interface Transport"
961                                 " Protocol\n");
962                 break;
963         case 0x80:
964                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
965                 break;
966         default:
967                 sprintf(buf+len, "Unknown 0x%02x\n",
968                                 vpd->protocol_identifier);
969                 break;
970         }
971
972         if (p_buf)
973                 strncpy(p_buf, buf, p_buf_len);
974         else
975                 pr_debug("%s", buf);
976 }
977
978 void
979 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
980 {
981         /*
982          * Check if the Protocol Identifier Valid (PIV) bit is set..
983          *
984          * from spc3r23.pdf section 7.5.1
985          */
986          if (page_83[1] & 0x80) {
987                 vpd->protocol_identifier = (page_83[0] & 0xf0);
988                 vpd->protocol_identifier_set = 1;
989                 transport_dump_vpd_proto_id(vpd, NULL, 0);
990         }
991 }
992 EXPORT_SYMBOL(transport_set_vpd_proto_id);
993
994 int transport_dump_vpd_assoc(
995         struct t10_vpd *vpd,
996         unsigned char *p_buf,
997         int p_buf_len)
998 {
999         unsigned char buf[VPD_TMP_BUF_SIZE];
1000         int ret = 0;
1001         int len;
1002
1003         memset(buf, 0, VPD_TMP_BUF_SIZE);
1004         len = sprintf(buf, "T10 VPD Identifier Association: ");
1005
1006         switch (vpd->association) {
1007         case 0x00:
1008                 sprintf(buf+len, "addressed logical unit\n");
1009                 break;
1010         case 0x10:
1011                 sprintf(buf+len, "target port\n");
1012                 break;
1013         case 0x20:
1014                 sprintf(buf+len, "SCSI target device\n");
1015                 break;
1016         default:
1017                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1018                 ret = -EINVAL;
1019                 break;
1020         }
1021
1022         if (p_buf)
1023                 strncpy(p_buf, buf, p_buf_len);
1024         else
1025                 pr_debug("%s", buf);
1026
1027         return ret;
1028 }
1029
1030 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1031 {
1032         /*
1033          * The VPD identification association..
1034          *
1035          * from spc3r23.pdf Section 7.6.3.1 Table 297
1036          */
1037         vpd->association = (page_83[1] & 0x30);
1038         return transport_dump_vpd_assoc(vpd, NULL, 0);
1039 }
1040 EXPORT_SYMBOL(transport_set_vpd_assoc);
1041
1042 int transport_dump_vpd_ident_type(
1043         struct t10_vpd *vpd,
1044         unsigned char *p_buf,
1045         int p_buf_len)
1046 {
1047         unsigned char buf[VPD_TMP_BUF_SIZE];
1048         int ret = 0;
1049         int len;
1050
1051         memset(buf, 0, VPD_TMP_BUF_SIZE);
1052         len = sprintf(buf, "T10 VPD Identifier Type: ");
1053
1054         switch (vpd->device_identifier_type) {
1055         case 0x00:
1056                 sprintf(buf+len, "Vendor specific\n");
1057                 break;
1058         case 0x01:
1059                 sprintf(buf+len, "T10 Vendor ID based\n");
1060                 break;
1061         case 0x02:
1062                 sprintf(buf+len, "EUI-64 based\n");
1063                 break;
1064         case 0x03:
1065                 sprintf(buf+len, "NAA\n");
1066                 break;
1067         case 0x04:
1068                 sprintf(buf+len, "Relative target port identifier\n");
1069                 break;
1070         case 0x08:
1071                 sprintf(buf+len, "SCSI name string\n");
1072                 break;
1073         default:
1074                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1075                                 vpd->device_identifier_type);
1076                 ret = -EINVAL;
1077                 break;
1078         }
1079
1080         if (p_buf) {
1081                 if (p_buf_len < strlen(buf)+1)
1082                         return -EINVAL;
1083                 strncpy(p_buf, buf, p_buf_len);
1084         } else {
1085                 pr_debug("%s", buf);
1086         }
1087
1088         return ret;
1089 }
1090
1091 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1092 {
1093         /*
1094          * The VPD identifier type..
1095          *
1096          * from spc3r23.pdf Section 7.6.3.1 Table 298
1097          */
1098         vpd->device_identifier_type = (page_83[1] & 0x0f);
1099         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1100 }
1101 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1102
1103 int transport_dump_vpd_ident(
1104         struct t10_vpd *vpd,
1105         unsigned char *p_buf,
1106         int p_buf_len)
1107 {
1108         unsigned char buf[VPD_TMP_BUF_SIZE];
1109         int ret = 0;
1110
1111         memset(buf, 0, VPD_TMP_BUF_SIZE);
1112
1113         switch (vpd->device_identifier_code_set) {
1114         case 0x01: /* Binary */
1115                 snprintf(buf, sizeof(buf),
1116                         "T10 VPD Binary Device Identifier: %s\n",
1117                         &vpd->device_identifier[0]);
1118                 break;
1119         case 0x02: /* ASCII */
1120                 snprintf(buf, sizeof(buf),
1121                         "T10 VPD ASCII Device Identifier: %s\n",
1122                         &vpd->device_identifier[0]);
1123                 break;
1124         case 0x03: /* UTF-8 */
1125                 snprintf(buf, sizeof(buf),
1126                         "T10 VPD UTF-8 Device Identifier: %s\n",
1127                         &vpd->device_identifier[0]);
1128                 break;
1129         default:
1130                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1131                         " 0x%02x", vpd->device_identifier_code_set);
1132                 ret = -EINVAL;
1133                 break;
1134         }
1135
1136         if (p_buf)
1137                 strncpy(p_buf, buf, p_buf_len);
1138         else
1139                 pr_debug("%s", buf);
1140
1141         return ret;
1142 }
1143
1144 int
1145 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1146 {
1147         static const char hex_str[] = "0123456789abcdef";
1148         int j = 0, i = 4; /* offset to start of the identifier */
1149
1150         /*
1151          * The VPD Code Set (encoding)
1152          *
1153          * from spc3r23.pdf Section 7.6.3.1 Table 296
1154          */
1155         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1156         switch (vpd->device_identifier_code_set) {
1157         case 0x01: /* Binary */
1158                 vpd->device_identifier[j++] =
1159                                 hex_str[vpd->device_identifier_type];
1160                 while (i < (4 + page_83[3])) {
1161                         vpd->device_identifier[j++] =
1162                                 hex_str[(page_83[i] & 0xf0) >> 4];
1163                         vpd->device_identifier[j++] =
1164                                 hex_str[page_83[i] & 0x0f];
1165                         i++;
1166                 }
1167                 break;
1168         case 0x02: /* ASCII */
1169         case 0x03: /* UTF-8 */
1170                 while (i < (4 + page_83[3]))
1171                         vpd->device_identifier[j++] = page_83[i++];
1172                 break;
1173         default:
1174                 break;
1175         }
1176
1177         return transport_dump_vpd_ident(vpd, NULL, 0);
1178 }
1179 EXPORT_SYMBOL(transport_set_vpd_ident);
1180
1181 static sense_reason_t
1182 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1183                                unsigned int size)
1184 {
1185         u32 mtl;
1186
1187         if (!cmd->se_tfo->max_data_sg_nents)
1188                 return TCM_NO_SENSE;
1189         /*
1190          * Check if fabric enforced maximum SGL entries per I/O descriptor
1191          * exceeds se_cmd->data_length.  If true, set SCF_UNDERFLOW_BIT +
1192          * residual_count and reduce original cmd->data_length to maximum
1193          * length based on single PAGE_SIZE entry scatter-lists.
1194          */
1195         mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1196         if (cmd->data_length > mtl) {
1197                 /*
1198                  * If an existing CDB overflow is present, calculate new residual
1199                  * based on CDB size minus fabric maximum transfer length.
1200                  *
1201                  * If an existing CDB underflow is present, calculate new residual
1202                  * based on original cmd->data_length minus fabric maximum transfer
1203                  * length.
1204                  *
1205                  * Otherwise, set the underflow residual based on cmd->data_length
1206                  * minus fabric maximum transfer length.
1207                  */
1208                 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1209                         cmd->residual_count = (size - mtl);
1210                 } else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1211                         u32 orig_dl = size + cmd->residual_count;
1212                         cmd->residual_count = (orig_dl - mtl);
1213                 } else {
1214                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1215                         cmd->residual_count = (cmd->data_length - mtl);
1216                 }
1217                 cmd->data_length = mtl;
1218                 /*
1219                  * Reset sbc_check_prot() calculated protection payload
1220                  * length based upon the new smaller MTL.
1221                  */
1222                 if (cmd->prot_length) {
1223                         u32 sectors = (mtl / dev->dev_attrib.block_size);
1224                         cmd->prot_length = dev->prot_length * sectors;
1225                 }
1226         }
1227         return TCM_NO_SENSE;
1228 }
1229
1230 sense_reason_t
1231 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1232 {
1233         struct se_device *dev = cmd->se_dev;
1234
1235         if (cmd->unknown_data_length) {
1236                 cmd->data_length = size;
1237         } else if (size != cmd->data_length) {
1238                 pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1239                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1240                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
1241                                 cmd->data_length, size, cmd->t_task_cdb[0]);
1242
1243                 if (cmd->data_direction == DMA_TO_DEVICE) {
1244                         if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1245                                 pr_err_ratelimited("Rejecting underflow/overflow"
1246                                                    " for WRITE data CDB\n");
1247                                 return TCM_INVALID_CDB_FIELD;
1248                         }
1249                         /*
1250                          * Some fabric drivers like iscsi-target still expect to
1251                          * always reject overflow writes.  Reject this case until
1252                          * full fabric driver level support for overflow writes
1253                          * is introduced tree-wide.
1254                          */
1255                         if (size > cmd->data_length) {
1256                                 pr_err_ratelimited("Rejecting overflow for"
1257                                                    " WRITE control CDB\n");
1258                                 return TCM_INVALID_CDB_FIELD;
1259                         }
1260                 }
1261                 /*
1262                  * Reject READ_* or WRITE_* with overflow/underflow for
1263                  * type SCF_SCSI_DATA_CDB.
1264                  */
1265                 if (dev->dev_attrib.block_size != 512)  {
1266                         pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1267                                 " CDB on non 512-byte sector setup subsystem"
1268                                 " plugin: %s\n", dev->transport->name);
1269                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1270                         return TCM_INVALID_CDB_FIELD;
1271                 }
1272                 /*
1273                  * For the overflow case keep the existing fabric provided
1274                  * ->data_length.  Otherwise for the underflow case, reset
1275                  * ->data_length to the smaller SCSI expected data transfer
1276                  * length.
1277                  */
1278                 if (size > cmd->data_length) {
1279                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1280                         cmd->residual_count = (size - cmd->data_length);
1281                 } else {
1282                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1283                         cmd->residual_count = (cmd->data_length - size);
1284                         cmd->data_length = size;
1285                 }
1286         }
1287
1288         return target_check_max_data_sg_nents(cmd, dev, size);
1289
1290 }
1291
1292 /*
1293  * Used by fabric modules containing a local struct se_cmd within their
1294  * fabric dependent per I/O descriptor.
1295  *
1296  * Preserves the value of @cmd->tag.
1297  */
1298 void transport_init_se_cmd(
1299         struct se_cmd *cmd,
1300         const struct target_core_fabric_ops *tfo,
1301         struct se_session *se_sess,
1302         u32 data_length,
1303         int data_direction,
1304         int task_attr,
1305         unsigned char *sense_buffer)
1306 {
1307         INIT_LIST_HEAD(&cmd->se_delayed_node);
1308         INIT_LIST_HEAD(&cmd->se_qf_node);
1309         INIT_LIST_HEAD(&cmd->se_cmd_list);
1310         INIT_LIST_HEAD(&cmd->state_list);
1311         init_completion(&cmd->t_transport_stop_comp);
1312         cmd->compl = NULL;
1313         spin_lock_init(&cmd->t_state_lock);
1314         INIT_WORK(&cmd->work, NULL);
1315         kref_init(&cmd->cmd_kref);
1316
1317         cmd->se_tfo = tfo;
1318         cmd->se_sess = se_sess;
1319         cmd->data_length = data_length;
1320         cmd->data_direction = data_direction;
1321         cmd->sam_task_attr = task_attr;
1322         cmd->sense_buffer = sense_buffer;
1323
1324         cmd->state_active = false;
1325 }
1326 EXPORT_SYMBOL(transport_init_se_cmd);
1327
1328 static sense_reason_t
1329 transport_check_alloc_task_attr(struct se_cmd *cmd)
1330 {
1331         struct se_device *dev = cmd->se_dev;
1332
1333         /*
1334          * Check if SAM Task Attribute emulation is enabled for this
1335          * struct se_device storage object
1336          */
1337         if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1338                 return 0;
1339
1340         if (cmd->sam_task_attr == TCM_ACA_TAG) {
1341                 pr_debug("SAM Task Attribute ACA"
1342                         " emulation is not supported\n");
1343                 return TCM_INVALID_CDB_FIELD;
1344         }
1345
1346         return 0;
1347 }
1348
1349 sense_reason_t
1350 target_setup_cmd_from_cdb(struct se_cmd *cmd, unsigned char *cdb)
1351 {
1352         struct se_device *dev = cmd->se_dev;
1353         sense_reason_t ret;
1354
1355         /*
1356          * Ensure that the received CDB is less than the max (252 + 8) bytes
1357          * for VARIABLE_LENGTH_CMD
1358          */
1359         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1360                 pr_err("Received SCSI CDB with command_size: %d that"
1361                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1362                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1363                 return TCM_INVALID_CDB_FIELD;
1364         }
1365         /*
1366          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1367          * allocate the additional extended CDB buffer now..  Otherwise
1368          * setup the pointer from __t_task_cdb to t_task_cdb.
1369          */
1370         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1371                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1372                                                 GFP_KERNEL);
1373                 if (!cmd->t_task_cdb) {
1374                         pr_err("Unable to allocate cmd->t_task_cdb"
1375                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1376                                 scsi_command_size(cdb),
1377                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1378                         return TCM_OUT_OF_RESOURCES;
1379                 }
1380         } else
1381                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1382         /*
1383          * Copy the original CDB into cmd->
1384          */
1385         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1386
1387         trace_target_sequencer_start(cmd);
1388
1389         ret = dev->transport->parse_cdb(cmd);
1390         if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1391                 pr_warn_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1392                                     cmd->se_tfo->get_fabric_name(),
1393                                     cmd->se_sess->se_node_acl->initiatorname,
1394                                     cmd->t_task_cdb[0]);
1395         if (ret)
1396                 return ret;
1397
1398         ret = transport_check_alloc_task_attr(cmd);
1399         if (ret)
1400                 return ret;
1401
1402         cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1403         atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1404         return 0;
1405 }
1406 EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1407
1408 /*
1409  * Used by fabric module frontends to queue tasks directly.
1410  * May only be used from process context.
1411  */
1412 int transport_handle_cdb_direct(
1413         struct se_cmd *cmd)
1414 {
1415         sense_reason_t ret;
1416
1417         if (!cmd->se_lun) {
1418                 dump_stack();
1419                 pr_err("cmd->se_lun is NULL\n");
1420                 return -EINVAL;
1421         }
1422         if (in_interrupt()) {
1423                 dump_stack();
1424                 pr_err("transport_generic_handle_cdb cannot be called"
1425                                 " from interrupt context\n");
1426                 return -EINVAL;
1427         }
1428         /*
1429          * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1430          * outstanding descriptors are handled correctly during shutdown via
1431          * transport_wait_for_tasks()
1432          *
1433          * Also, we don't take cmd->t_state_lock here as we only expect
1434          * this to be called for initial descriptor submission.
1435          */
1436         cmd->t_state = TRANSPORT_NEW_CMD;
1437         cmd->transport_state |= CMD_T_ACTIVE;
1438
1439         /*
1440          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1441          * so follow TRANSPORT_NEW_CMD processing thread context usage
1442          * and call transport_generic_request_failure() if necessary..
1443          */
1444         ret = transport_generic_new_cmd(cmd);
1445         if (ret)
1446                 transport_generic_request_failure(cmd, ret);
1447         return 0;
1448 }
1449 EXPORT_SYMBOL(transport_handle_cdb_direct);
1450
1451 sense_reason_t
1452 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1453                 u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1454 {
1455         if (!sgl || !sgl_count)
1456                 return 0;
1457
1458         /*
1459          * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1460          * scatterlists already have been set to follow what the fabric
1461          * passes for the original expected data transfer length.
1462          */
1463         if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1464                 pr_warn("Rejecting SCSI DATA overflow for fabric using"
1465                         " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1466                 return TCM_INVALID_CDB_FIELD;
1467         }
1468
1469         cmd->t_data_sg = sgl;
1470         cmd->t_data_nents = sgl_count;
1471         cmd->t_bidi_data_sg = sgl_bidi;
1472         cmd->t_bidi_data_nents = sgl_bidi_count;
1473
1474         cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1475         return 0;
1476 }
1477
1478 /**
1479  * target_submit_cmd_map_sgls - lookup unpacked lun and submit uninitialized
1480  *                       se_cmd + use pre-allocated SGL memory.
1481  *
1482  * @se_cmd: command descriptor to submit
1483  * @se_sess: associated se_sess for endpoint
1484  * @cdb: pointer to SCSI CDB
1485  * @sense: pointer to SCSI sense buffer
1486  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1487  * @data_length: fabric expected data transfer length
1488  * @task_attr: SAM task attribute
1489  * @data_dir: DMA data direction
1490  * @flags: flags for command submission from target_sc_flags_tables
1491  * @sgl: struct scatterlist memory for unidirectional mapping
1492  * @sgl_count: scatterlist count for unidirectional mapping
1493  * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1494  * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1495  * @sgl_prot: struct scatterlist memory protection information
1496  * @sgl_prot_count: scatterlist count for protection information
1497  *
1498  * Task tags are supported if the caller has set @se_cmd->tag.
1499  *
1500  * Returns non zero to signal active I/O shutdown failure.  All other
1501  * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1502  * but still return zero here.
1503  *
1504  * This may only be called from process context, and also currently
1505  * assumes internal allocation of fabric payload buffer by target-core.
1506  */
1507 int target_submit_cmd_map_sgls(struct se_cmd *se_cmd, struct se_session *se_sess,
1508                 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1509                 u32 data_length, int task_attr, int data_dir, int flags,
1510                 struct scatterlist *sgl, u32 sgl_count,
1511                 struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1512                 struct scatterlist *sgl_prot, u32 sgl_prot_count)
1513 {
1514         struct se_portal_group *se_tpg;
1515         sense_reason_t rc;
1516         int ret;
1517
1518         se_tpg = se_sess->se_tpg;
1519         BUG_ON(!se_tpg);
1520         BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1521         BUG_ON(in_interrupt());
1522         /*
1523          * Initialize se_cmd for target operation.  From this point
1524          * exceptions are handled by sending exception status via
1525          * target_core_fabric_ops->queue_status() callback
1526          */
1527         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1528                                 data_length, data_dir, task_attr, sense);
1529
1530         if (flags & TARGET_SCF_USE_CPUID)
1531                 se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1532         else
1533                 se_cmd->cpuid = WORK_CPU_UNBOUND;
1534
1535         if (flags & TARGET_SCF_UNKNOWN_SIZE)
1536                 se_cmd->unknown_data_length = 1;
1537         /*
1538          * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1539          * se_sess->sess_cmd_list.  A second kref_get here is necessary
1540          * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1541          * kref_put() to happen during fabric packet acknowledgement.
1542          */
1543         ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1544         if (ret)
1545                 return ret;
1546         /*
1547          * Signal bidirectional data payloads to target-core
1548          */
1549         if (flags & TARGET_SCF_BIDI_OP)
1550                 se_cmd->se_cmd_flags |= SCF_BIDI;
1551         /*
1552          * Locate se_lun pointer and attach it to struct se_cmd
1553          */
1554         rc = transport_lookup_cmd_lun(se_cmd, unpacked_lun);
1555         if (rc) {
1556                 transport_send_check_condition_and_sense(se_cmd, rc, 0);
1557                 target_put_sess_cmd(se_cmd);
1558                 return 0;
1559         }
1560
1561         rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1562         if (rc != 0) {
1563                 transport_generic_request_failure(se_cmd, rc);
1564                 return 0;
1565         }
1566
1567         /*
1568          * Save pointers for SGLs containing protection information,
1569          * if present.
1570          */
1571         if (sgl_prot_count) {
1572                 se_cmd->t_prot_sg = sgl_prot;
1573                 se_cmd->t_prot_nents = sgl_prot_count;
1574                 se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1575         }
1576
1577         /*
1578          * When a non zero sgl_count has been passed perform SGL passthrough
1579          * mapping for pre-allocated fabric memory instead of having target
1580          * core perform an internal SGL allocation..
1581          */
1582         if (sgl_count != 0) {
1583                 BUG_ON(!sgl);
1584
1585                 /*
1586                  * A work-around for tcm_loop as some userspace code via
1587                  * scsi-generic do not memset their associated read buffers,
1588                  * so go ahead and do that here for type non-data CDBs.  Also
1589                  * note that this is currently guaranteed to be a single SGL
1590                  * for this case by target core in target_setup_cmd_from_cdb()
1591                  * -> transport_generic_cmd_sequencer().
1592                  */
1593                 if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1594                      se_cmd->data_direction == DMA_FROM_DEVICE) {
1595                         unsigned char *buf = NULL;
1596
1597                         if (sgl)
1598                                 buf = kmap(sg_page(sgl)) + sgl->offset;
1599
1600                         if (buf) {
1601                                 memset(buf, 0, sgl->length);
1602                                 kunmap(sg_page(sgl));
1603                         }
1604                 }
1605
1606                 rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1607                                 sgl_bidi, sgl_bidi_count);
1608                 if (rc != 0) {
1609                         transport_generic_request_failure(se_cmd, rc);
1610                         return 0;
1611                 }
1612         }
1613
1614         /*
1615          * Check if we need to delay processing because of ALUA
1616          * Active/NonOptimized primary access state..
1617          */
1618         core_alua_check_nonop_delay(se_cmd);
1619
1620         transport_handle_cdb_direct(se_cmd);
1621         return 0;
1622 }
1623 EXPORT_SYMBOL(target_submit_cmd_map_sgls);
1624
1625 /**
1626  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1627  *
1628  * @se_cmd: command descriptor to submit
1629  * @se_sess: associated se_sess for endpoint
1630  * @cdb: pointer to SCSI CDB
1631  * @sense: pointer to SCSI sense buffer
1632  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1633  * @data_length: fabric expected data transfer length
1634  * @task_attr: SAM task attribute
1635  * @data_dir: DMA data direction
1636  * @flags: flags for command submission from target_sc_flags_tables
1637  *
1638  * Task tags are supported if the caller has set @se_cmd->tag.
1639  *
1640  * Returns non zero to signal active I/O shutdown failure.  All other
1641  * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1642  * but still return zero here.
1643  *
1644  * This may only be called from process context, and also currently
1645  * assumes internal allocation of fabric payload buffer by target-core.
1646  *
1647  * It also assumes interal target core SGL memory allocation.
1648  */
1649 int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1650                 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1651                 u32 data_length, int task_attr, int data_dir, int flags)
1652 {
1653         return target_submit_cmd_map_sgls(se_cmd, se_sess, cdb, sense,
1654                         unpacked_lun, data_length, task_attr, data_dir,
1655                         flags, NULL, 0, NULL, 0, NULL, 0);
1656 }
1657 EXPORT_SYMBOL(target_submit_cmd);
1658
1659 static void target_complete_tmr_failure(struct work_struct *work)
1660 {
1661         struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1662
1663         se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1664         se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1665
1666         transport_lun_remove_cmd(se_cmd);
1667         transport_cmd_check_stop_to_fabric(se_cmd);
1668 }
1669
1670 static bool target_lookup_lun_from_tag(struct se_session *se_sess, u64 tag,
1671                                        u64 *unpacked_lun)
1672 {
1673         struct se_cmd *se_cmd;
1674         unsigned long flags;
1675         bool ret = false;
1676
1677         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
1678         list_for_each_entry(se_cmd, &se_sess->sess_cmd_list, se_cmd_list) {
1679                 if (se_cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
1680                         continue;
1681
1682                 if (se_cmd->tag == tag) {
1683                         *unpacked_lun = se_cmd->orig_fe_lun;
1684                         ret = true;
1685                         break;
1686                 }
1687         }
1688         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
1689
1690         return ret;
1691 }
1692
1693 /**
1694  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1695  *                     for TMR CDBs
1696  *
1697  * @se_cmd: command descriptor to submit
1698  * @se_sess: associated se_sess for endpoint
1699  * @sense: pointer to SCSI sense buffer
1700  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1701  * @fabric_tmr_ptr: fabric context for TMR req
1702  * @tm_type: Type of TM request
1703  * @gfp: gfp type for caller
1704  * @tag: referenced task tag for TMR_ABORT_TASK
1705  * @flags: submit cmd flags
1706  *
1707  * Callable from all contexts.
1708  **/
1709
1710 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1711                 unsigned char *sense, u64 unpacked_lun,
1712                 void *fabric_tmr_ptr, unsigned char tm_type,
1713                 gfp_t gfp, u64 tag, int flags)
1714 {
1715         struct se_portal_group *se_tpg;
1716         int ret;
1717
1718         se_tpg = se_sess->se_tpg;
1719         BUG_ON(!se_tpg);
1720
1721         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1722                               0, DMA_NONE, TCM_SIMPLE_TAG, sense);
1723         /*
1724          * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1725          * allocation failure.
1726          */
1727         ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1728         if (ret < 0)
1729                 return -ENOMEM;
1730
1731         if (tm_type == TMR_ABORT_TASK)
1732                 se_cmd->se_tmr_req->ref_task_tag = tag;
1733
1734         /* See target_submit_cmd for commentary */
1735         ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1736         if (ret) {
1737                 core_tmr_release_req(se_cmd->se_tmr_req);
1738                 return ret;
1739         }
1740         /*
1741          * If this is ABORT_TASK with no explicit fabric provided LUN,
1742          * go ahead and search active session tags for a match to figure
1743          * out unpacked_lun for the original se_cmd.
1744          */
1745         if (tm_type == TMR_ABORT_TASK && (flags & TARGET_SCF_LOOKUP_LUN_FROM_TAG)) {
1746                 if (!target_lookup_lun_from_tag(se_sess, tag, &unpacked_lun))
1747                         goto failure;
1748         }
1749
1750         ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1751         if (ret)
1752                 goto failure;
1753
1754         transport_generic_handle_tmr(se_cmd);
1755         return 0;
1756
1757         /*
1758          * For callback during failure handling, push this work off
1759          * to process context with TMR_LUN_DOES_NOT_EXIST status.
1760          */
1761 failure:
1762         INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1763         schedule_work(&se_cmd->work);
1764         return 0;
1765 }
1766 EXPORT_SYMBOL(target_submit_tmr);
1767
1768 /*
1769  * Handle SAM-esque emulation for generic transport request failures.
1770  */
1771 void transport_generic_request_failure(struct se_cmd *cmd,
1772                 sense_reason_t sense_reason)
1773 {
1774         int ret = 0, post_ret = 0;
1775
1776         pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
1777                  sense_reason);
1778         target_show_cmd("-----[ ", cmd);
1779
1780         /*
1781          * For SAM Task Attribute emulation for failed struct se_cmd
1782          */
1783         transport_complete_task_attr(cmd);
1784
1785         /*
1786          * Handle special case for COMPARE_AND_WRITE failure, where the
1787          * callback is expected to drop the per device ->caw_sem.
1788          */
1789         if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
1790              cmd->transport_complete_callback)
1791                 cmd->transport_complete_callback(cmd, false, &post_ret);
1792
1793         if (transport_check_aborted_status(cmd, 1))
1794                 return;
1795
1796         switch (sense_reason) {
1797         case TCM_NON_EXISTENT_LUN:
1798         case TCM_UNSUPPORTED_SCSI_OPCODE:
1799         case TCM_INVALID_CDB_FIELD:
1800         case TCM_INVALID_PARAMETER_LIST:
1801         case TCM_PARAMETER_LIST_LENGTH_ERROR:
1802         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1803         case TCM_UNKNOWN_MODE_PAGE:
1804         case TCM_WRITE_PROTECTED:
1805         case TCM_ADDRESS_OUT_OF_RANGE:
1806         case TCM_CHECK_CONDITION_ABORT_CMD:
1807         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1808         case TCM_CHECK_CONDITION_NOT_READY:
1809         case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
1810         case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
1811         case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
1812         case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
1813         case TCM_TOO_MANY_TARGET_DESCS:
1814         case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
1815         case TCM_TOO_MANY_SEGMENT_DESCS:
1816         case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
1817                 break;
1818         case TCM_OUT_OF_RESOURCES:
1819                 cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
1820                 goto queue_status;
1821         case TCM_LUN_BUSY:
1822                 cmd->scsi_status = SAM_STAT_BUSY;
1823                 goto queue_status;
1824         case TCM_RESERVATION_CONFLICT:
1825                 /*
1826                  * No SENSE Data payload for this case, set SCSI Status
1827                  * and queue the response to $FABRIC_MOD.
1828                  *
1829                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1830                  */
1831                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1832                 /*
1833                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1834                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1835                  * CONFLICT STATUS.
1836                  *
1837                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1838                  */
1839                 if (cmd->se_sess &&
1840                     cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl == 2) {
1841                         target_ua_allocate_lun(cmd->se_sess->se_node_acl,
1842                                                cmd->orig_fe_lun, 0x2C,
1843                                         ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1844                 }
1845
1846                 goto queue_status;
1847         default:
1848                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1849                         cmd->t_task_cdb[0], sense_reason);
1850                 sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1851                 break;
1852         }
1853
1854         ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
1855         if (ret)
1856                 goto queue_full;
1857
1858 check_stop:
1859         transport_lun_remove_cmd(cmd);
1860         transport_cmd_check_stop_to_fabric(cmd);
1861         return;
1862
1863 queue_status:
1864         trace_target_cmd_complete(cmd);
1865         ret = cmd->se_tfo->queue_status(cmd);
1866         if (!ret)
1867                 goto check_stop;
1868 queue_full:
1869         transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
1870 }
1871 EXPORT_SYMBOL(transport_generic_request_failure);
1872
1873 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
1874 {
1875         sense_reason_t ret;
1876
1877         if (!cmd->execute_cmd) {
1878                 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1879                 goto err;
1880         }
1881         if (do_checks) {
1882                 /*
1883                  * Check for an existing UNIT ATTENTION condition after
1884                  * target_handle_task_attr() has done SAM task attr
1885                  * checking, and possibly have already defered execution
1886                  * out to target_restart_delayed_cmds() context.
1887                  */
1888                 ret = target_scsi3_ua_check(cmd);
1889                 if (ret)
1890                         goto err;
1891
1892                 ret = target_alua_state_check(cmd);
1893                 if (ret)
1894                         goto err;
1895
1896                 ret = target_check_reservation(cmd);
1897                 if (ret) {
1898                         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1899                         goto err;
1900                 }
1901         }
1902
1903         ret = cmd->execute_cmd(cmd);
1904         if (!ret)
1905                 return;
1906 err:
1907         spin_lock_irq(&cmd->t_state_lock);
1908         cmd->transport_state &= ~CMD_T_SENT;
1909         spin_unlock_irq(&cmd->t_state_lock);
1910
1911         transport_generic_request_failure(cmd, ret);
1912 }
1913
1914 static int target_write_prot_action(struct se_cmd *cmd)
1915 {
1916         u32 sectors;
1917         /*
1918          * Perform WRITE_INSERT of PI using software emulation when backend
1919          * device has PI enabled, if the transport has not already generated
1920          * PI using hardware WRITE_INSERT offload.
1921          */
1922         switch (cmd->prot_op) {
1923         case TARGET_PROT_DOUT_INSERT:
1924                 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
1925                         sbc_dif_generate(cmd);
1926                 break;
1927         case TARGET_PROT_DOUT_STRIP:
1928                 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
1929                         break;
1930
1931                 sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
1932                 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
1933                                              sectors, 0, cmd->t_prot_sg, 0);
1934                 if (unlikely(cmd->pi_err)) {
1935                         spin_lock_irq(&cmd->t_state_lock);
1936                         cmd->transport_state &= ~CMD_T_SENT;
1937                         spin_unlock_irq(&cmd->t_state_lock);
1938                         transport_generic_request_failure(cmd, cmd->pi_err);
1939                         return -1;
1940                 }
1941                 break;
1942         default:
1943                 break;
1944         }
1945
1946         return 0;
1947 }
1948
1949 static bool target_handle_task_attr(struct se_cmd *cmd)
1950 {
1951         struct se_device *dev = cmd->se_dev;
1952
1953         if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1954                 return false;
1955
1956         cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
1957
1958         /*
1959          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1960          * to allow the passed struct se_cmd list of tasks to the front of the list.
1961          */
1962         switch (cmd->sam_task_attr) {
1963         case TCM_HEAD_TAG:
1964                 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
1965                          cmd->t_task_cdb[0]);
1966                 return false;
1967         case TCM_ORDERED_TAG:
1968                 atomic_inc_mb(&dev->dev_ordered_sync);
1969
1970                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
1971                          cmd->t_task_cdb[0]);
1972
1973                 /*
1974                  * Execute an ORDERED command if no other older commands
1975                  * exist that need to be completed first.
1976                  */
1977                 if (!atomic_read(&dev->simple_cmds))
1978                         return false;
1979                 break;
1980         default:
1981                 /*
1982                  * For SIMPLE and UNTAGGED Task Attribute commands
1983                  */
1984                 atomic_inc_mb(&dev->simple_cmds);
1985                 break;
1986         }
1987
1988         if (atomic_read(&dev->dev_ordered_sync) == 0)
1989                 return false;
1990
1991         spin_lock(&dev->delayed_cmd_lock);
1992         list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
1993         spin_unlock(&dev->delayed_cmd_lock);
1994
1995         pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
1996                 cmd->t_task_cdb[0], cmd->sam_task_attr);
1997         return true;
1998 }
1999
2000 static int __transport_check_aborted_status(struct se_cmd *, int);
2001
2002 void target_execute_cmd(struct se_cmd *cmd)
2003 {
2004         /*
2005          * Determine if frontend context caller is requesting the stopping of
2006          * this command for frontend exceptions.
2007          *
2008          * If the received CDB has aleady been aborted stop processing it here.
2009          */
2010         spin_lock_irq(&cmd->t_state_lock);
2011         if (__transport_check_aborted_status(cmd, 1)) {
2012                 spin_unlock_irq(&cmd->t_state_lock);
2013                 return;
2014         }
2015         if (cmd->transport_state & CMD_T_STOP) {
2016                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2017                         __func__, __LINE__, cmd->tag);
2018
2019                 spin_unlock_irq(&cmd->t_state_lock);
2020                 complete_all(&cmd->t_transport_stop_comp);
2021                 return;
2022         }
2023
2024         cmd->t_state = TRANSPORT_PROCESSING;
2025         cmd->transport_state &= ~CMD_T_PRE_EXECUTE;
2026         cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2027         spin_unlock_irq(&cmd->t_state_lock);
2028
2029         if (target_write_prot_action(cmd))
2030                 return;
2031
2032         if (target_handle_task_attr(cmd)) {
2033                 spin_lock_irq(&cmd->t_state_lock);
2034                 cmd->transport_state &= ~CMD_T_SENT;
2035                 spin_unlock_irq(&cmd->t_state_lock);
2036                 return;
2037         }
2038
2039         __target_execute_cmd(cmd, true);
2040 }
2041 EXPORT_SYMBOL(target_execute_cmd);
2042
2043 /*
2044  * Process all commands up to the last received ORDERED task attribute which
2045  * requires another blocking boundary
2046  */
2047 static void target_restart_delayed_cmds(struct se_device *dev)
2048 {
2049         for (;;) {
2050                 struct se_cmd *cmd;
2051
2052                 spin_lock(&dev->delayed_cmd_lock);
2053                 if (list_empty(&dev->delayed_cmd_list)) {
2054                         spin_unlock(&dev->delayed_cmd_lock);
2055                         break;
2056                 }
2057
2058                 cmd = list_entry(dev->delayed_cmd_list.next,
2059                                  struct se_cmd, se_delayed_node);
2060                 list_del(&cmd->se_delayed_node);
2061                 spin_unlock(&dev->delayed_cmd_lock);
2062
2063                 cmd->transport_state |= CMD_T_SENT;
2064
2065                 __target_execute_cmd(cmd, true);
2066
2067                 if (cmd->sam_task_attr == TCM_ORDERED_TAG)
2068                         break;
2069         }
2070 }
2071
2072 /*
2073  * Called from I/O completion to determine which dormant/delayed
2074  * and ordered cmds need to have their tasks added to the execution queue.
2075  */
2076 static void transport_complete_task_attr(struct se_cmd *cmd)
2077 {
2078         struct se_device *dev = cmd->se_dev;
2079
2080         if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2081                 return;
2082
2083         if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2084                 goto restart;
2085
2086         if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2087                 atomic_dec_mb(&dev->simple_cmds);
2088                 dev->dev_cur_ordered_id++;
2089         } else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2090                 dev->dev_cur_ordered_id++;
2091                 pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2092                          dev->dev_cur_ordered_id);
2093         } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2094                 atomic_dec_mb(&dev->dev_ordered_sync);
2095
2096                 dev->dev_cur_ordered_id++;
2097                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2098                          dev->dev_cur_ordered_id);
2099         }
2100         cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2101
2102 restart:
2103         target_restart_delayed_cmds(dev);
2104 }
2105
2106 static void transport_complete_qf(struct se_cmd *cmd)
2107 {
2108         int ret = 0;
2109
2110         transport_complete_task_attr(cmd);
2111         /*
2112          * If a fabric driver ->write_pending() or ->queue_data_in() callback
2113          * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2114          * the same callbacks should not be retried.  Return CHECK_CONDITION
2115          * if a scsi_status is not already set.
2116          *
2117          * If a fabric driver ->queue_status() has returned non zero, always
2118          * keep retrying no matter what..
2119          */
2120         if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2121                 if (cmd->scsi_status)
2122                         goto queue_status;
2123
2124                 translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2125                 goto queue_status;
2126         }
2127
2128         /*
2129          * Check if we need to send a sense buffer from
2130          * the struct se_cmd in question. We do NOT want
2131          * to take this path of the IO has been marked as
2132          * needing to be treated like a "normal read". This
2133          * is the case if it's a tape read, and either the
2134          * FM, EOM, or ILI bits are set, but there is no
2135          * sense data.
2136          */
2137         if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2138             cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2139                 goto queue_status;
2140
2141         switch (cmd->data_direction) {
2142         case DMA_FROM_DEVICE:
2143                 /* queue status if not treating this as a normal read */
2144                 if (cmd->scsi_status &&
2145                     !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2146                         goto queue_status;
2147
2148                 trace_target_cmd_complete(cmd);
2149                 ret = cmd->se_tfo->queue_data_in(cmd);
2150                 break;
2151         case DMA_TO_DEVICE:
2152                 if (cmd->se_cmd_flags & SCF_BIDI) {
2153                         ret = cmd->se_tfo->queue_data_in(cmd);
2154                         break;
2155                 }
2156                 /* fall through */
2157         case DMA_NONE:
2158 queue_status:
2159                 trace_target_cmd_complete(cmd);
2160                 ret = cmd->se_tfo->queue_status(cmd);
2161                 break;
2162         default:
2163                 break;
2164         }
2165
2166         if (ret < 0) {
2167                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2168                 return;
2169         }
2170         transport_lun_remove_cmd(cmd);
2171         transport_cmd_check_stop_to_fabric(cmd);
2172 }
2173
2174 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2175                                         int err, bool write_pending)
2176 {
2177         /*
2178          * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2179          * ->queue_data_in() callbacks from new process context.
2180          *
2181          * Otherwise for other errors, transport_complete_qf() will send
2182          * CHECK_CONDITION via ->queue_status() instead of attempting to
2183          * retry associated fabric driver data-transfer callbacks.
2184          */
2185         if (err == -EAGAIN || err == -ENOMEM) {
2186                 cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2187                                                  TRANSPORT_COMPLETE_QF_OK;
2188         } else {
2189                 pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2190                 cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2191         }
2192
2193         spin_lock_irq(&dev->qf_cmd_lock);
2194         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2195         atomic_inc_mb(&dev->dev_qf_count);
2196         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2197
2198         schedule_work(&cmd->se_dev->qf_work_queue);
2199 }
2200
2201 static bool target_read_prot_action(struct se_cmd *cmd)
2202 {
2203         switch (cmd->prot_op) {
2204         case TARGET_PROT_DIN_STRIP:
2205                 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2206                         u32 sectors = cmd->data_length >>
2207                                   ilog2(cmd->se_dev->dev_attrib.block_size);
2208
2209                         cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2210                                                      sectors, 0, cmd->t_prot_sg,
2211                                                      0);
2212                         if (cmd->pi_err)
2213                                 return true;
2214                 }
2215                 break;
2216         case TARGET_PROT_DIN_INSERT:
2217                 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2218                         break;
2219
2220                 sbc_dif_generate(cmd);
2221                 break;
2222         default:
2223                 break;
2224         }
2225
2226         return false;
2227 }
2228
2229 static void target_complete_ok_work(struct work_struct *work)
2230 {
2231         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2232         int ret;
2233
2234         /*
2235          * Check if we need to move delayed/dormant tasks from cmds on the
2236          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2237          * Attribute.
2238          */
2239         transport_complete_task_attr(cmd);
2240
2241         /*
2242          * Check to schedule QUEUE_FULL work, or execute an existing
2243          * cmd->transport_qf_callback()
2244          */
2245         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2246                 schedule_work(&cmd->se_dev->qf_work_queue);
2247
2248         /*
2249          * Check if we need to send a sense buffer from
2250          * the struct se_cmd in question. We do NOT want
2251          * to take this path of the IO has been marked as
2252          * needing to be treated like a "normal read". This
2253          * is the case if it's a tape read, and either the
2254          * FM, EOM, or ILI bits are set, but there is no
2255          * sense data.
2256          */
2257         if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2258             cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2259                 WARN_ON(!cmd->scsi_status);
2260                 ret = transport_send_check_condition_and_sense(
2261                                         cmd, 0, 1);
2262                 if (ret)
2263                         goto queue_full;
2264
2265                 transport_lun_remove_cmd(cmd);
2266                 transport_cmd_check_stop_to_fabric(cmd);
2267                 return;
2268         }
2269         /*
2270          * Check for a callback, used by amongst other things
2271          * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2272          */
2273         if (cmd->transport_complete_callback) {
2274                 sense_reason_t rc;
2275                 bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2276                 bool zero_dl = !(cmd->data_length);
2277                 int post_ret = 0;
2278
2279                 rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2280                 if (!rc && !post_ret) {
2281                         if (caw && zero_dl)
2282                                 goto queue_rsp;
2283
2284                         return;
2285                 } else if (rc) {
2286                         ret = transport_send_check_condition_and_sense(cmd,
2287                                                 rc, 0);
2288                         if (ret)
2289                                 goto queue_full;
2290
2291                         transport_lun_remove_cmd(cmd);
2292                         transport_cmd_check_stop_to_fabric(cmd);
2293                         return;
2294                 }
2295         }
2296
2297 queue_rsp:
2298         switch (cmd->data_direction) {
2299         case DMA_FROM_DEVICE:
2300                 /*
2301                  * if this is a READ-type IO, but SCSI status
2302                  * is set, then skip returning data and just
2303                  * return the status -- unless this IO is marked
2304                  * as needing to be treated as a normal read,
2305                  * in which case we want to go ahead and return
2306                  * the data. This happens, for example, for tape
2307                  * reads with the FM, EOM, or ILI bits set, with
2308                  * no sense data.
2309                  */
2310                 if (cmd->scsi_status &&
2311                     !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2312                         goto queue_status;
2313
2314                 atomic_long_add(cmd->data_length,
2315                                 &cmd->se_lun->lun_stats.tx_data_octets);
2316                 /*
2317                  * Perform READ_STRIP of PI using software emulation when
2318                  * backend had PI enabled, if the transport will not be
2319                  * performing hardware READ_STRIP offload.
2320                  */
2321                 if (target_read_prot_action(cmd)) {
2322                         ret = transport_send_check_condition_and_sense(cmd,
2323                                                 cmd->pi_err, 0);
2324                         if (ret)
2325                                 goto queue_full;
2326
2327                         transport_lun_remove_cmd(cmd);
2328                         transport_cmd_check_stop_to_fabric(cmd);
2329                         return;
2330                 }
2331
2332                 trace_target_cmd_complete(cmd);
2333                 ret = cmd->se_tfo->queue_data_in(cmd);
2334                 if (ret)
2335                         goto queue_full;
2336                 break;
2337         case DMA_TO_DEVICE:
2338                 atomic_long_add(cmd->data_length,
2339                                 &cmd->se_lun->lun_stats.rx_data_octets);
2340                 /*
2341                  * Check if we need to send READ payload for BIDI-COMMAND
2342                  */
2343                 if (cmd->se_cmd_flags & SCF_BIDI) {
2344                         atomic_long_add(cmd->data_length,
2345                                         &cmd->se_lun->lun_stats.tx_data_octets);
2346                         ret = cmd->se_tfo->queue_data_in(cmd);
2347                         if (ret)
2348                                 goto queue_full;
2349                         break;
2350                 }
2351                 /* fall through */
2352         case DMA_NONE:
2353 queue_status:
2354                 trace_target_cmd_complete(cmd);
2355                 ret = cmd->se_tfo->queue_status(cmd);
2356                 if (ret)
2357                         goto queue_full;
2358                 break;
2359         default:
2360                 break;
2361         }
2362
2363         transport_lun_remove_cmd(cmd);
2364         transport_cmd_check_stop_to_fabric(cmd);
2365         return;
2366
2367 queue_full:
2368         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2369                 " data_direction: %d\n", cmd, cmd->data_direction);
2370
2371         transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2372 }
2373
2374 void target_free_sgl(struct scatterlist *sgl, int nents)
2375 {
2376         sgl_free_n_order(sgl, nents, 0);
2377 }
2378 EXPORT_SYMBOL(target_free_sgl);
2379
2380 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2381 {
2382         /*
2383          * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2384          * emulation, and free + reset pointers if necessary..
2385          */
2386         if (!cmd->t_data_sg_orig)
2387                 return;
2388
2389         kfree(cmd->t_data_sg);
2390         cmd->t_data_sg = cmd->t_data_sg_orig;
2391         cmd->t_data_sg_orig = NULL;
2392         cmd->t_data_nents = cmd->t_data_nents_orig;
2393         cmd->t_data_nents_orig = 0;
2394 }
2395
2396 static inline void transport_free_pages(struct se_cmd *cmd)
2397 {
2398         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2399                 target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2400                 cmd->t_prot_sg = NULL;
2401                 cmd->t_prot_nents = 0;
2402         }
2403
2404         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2405                 /*
2406                  * Release special case READ buffer payload required for
2407                  * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2408                  */
2409                 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2410                         target_free_sgl(cmd->t_bidi_data_sg,
2411                                            cmd->t_bidi_data_nents);
2412                         cmd->t_bidi_data_sg = NULL;
2413                         cmd->t_bidi_data_nents = 0;
2414                 }
2415                 transport_reset_sgl_orig(cmd);
2416                 return;
2417         }
2418         transport_reset_sgl_orig(cmd);
2419
2420         target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2421         cmd->t_data_sg = NULL;
2422         cmd->t_data_nents = 0;
2423
2424         target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2425         cmd->t_bidi_data_sg = NULL;
2426         cmd->t_bidi_data_nents = 0;
2427 }
2428
2429 void *transport_kmap_data_sg(struct se_cmd *cmd)
2430 {
2431         struct scatterlist *sg = cmd->t_data_sg;
2432         struct page **pages;
2433         int i;
2434
2435         /*
2436          * We need to take into account a possible offset here for fabrics like
2437          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2438          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2439          */
2440         if (!cmd->t_data_nents)
2441                 return NULL;
2442
2443         BUG_ON(!sg);
2444         if (cmd->t_data_nents == 1)
2445                 return kmap(sg_page(sg)) + sg->offset;
2446
2447         /* >1 page. use vmap */
2448         pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2449         if (!pages)
2450                 return NULL;
2451
2452         /* convert sg[] to pages[] */
2453         for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2454                 pages[i] = sg_page(sg);
2455         }
2456
2457         cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2458         kfree(pages);
2459         if (!cmd->t_data_vmap)
2460                 return NULL;
2461
2462         return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2463 }
2464 EXPORT_SYMBOL(transport_kmap_data_sg);
2465
2466 void transport_kunmap_data_sg(struct se_cmd *cmd)
2467 {
2468         if (!cmd->t_data_nents) {
2469                 return;
2470         } else if (cmd->t_data_nents == 1) {
2471                 kunmap(sg_page(cmd->t_data_sg));
2472                 return;
2473         }
2474
2475         vunmap(cmd->t_data_vmap);
2476         cmd->t_data_vmap = NULL;
2477 }
2478 EXPORT_SYMBOL(transport_kunmap_data_sg);
2479
2480 int
2481 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2482                  bool zero_page, bool chainable)
2483 {
2484         gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2485
2486         *sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2487         return *sgl ? 0 : -ENOMEM;
2488 }
2489 EXPORT_SYMBOL(target_alloc_sgl);
2490
2491 /*
2492  * Allocate any required resources to execute the command.  For writes we
2493  * might not have the payload yet, so notify the fabric via a call to
2494  * ->write_pending instead. Otherwise place it on the execution queue.
2495  */
2496 sense_reason_t
2497 transport_generic_new_cmd(struct se_cmd *cmd)
2498 {
2499         unsigned long flags;
2500         int ret = 0;
2501         bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2502
2503         if (cmd->prot_op != TARGET_PROT_NORMAL &&
2504             !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2505                 ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2506                                        cmd->prot_length, true, false);
2507                 if (ret < 0)
2508                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2509         }
2510
2511         /*
2512          * Determine is the TCM fabric module has already allocated physical
2513          * memory, and is directly calling transport_generic_map_mem_to_cmd()
2514          * beforehand.
2515          */
2516         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2517             cmd->data_length) {
2518
2519                 if ((cmd->se_cmd_flags & SCF_BIDI) ||
2520                     (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2521                         u32 bidi_length;
2522
2523                         if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2524                                 bidi_length = cmd->t_task_nolb *
2525                                               cmd->se_dev->dev_attrib.block_size;
2526                         else
2527                                 bidi_length = cmd->data_length;
2528
2529                         ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2530                                                &cmd->t_bidi_data_nents,
2531                                                bidi_length, zero_flag, false);
2532                         if (ret < 0)
2533                                 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2534                 }
2535
2536                 ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2537                                        cmd->data_length, zero_flag, false);
2538                 if (ret < 0)
2539                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2540         } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2541                     cmd->data_length) {
2542                 /*
2543                  * Special case for COMPARE_AND_WRITE with fabrics
2544                  * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2545                  */
2546                 u32 caw_length = cmd->t_task_nolb *
2547                                  cmd->se_dev->dev_attrib.block_size;
2548
2549                 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2550                                        &cmd->t_bidi_data_nents,
2551                                        caw_length, zero_flag, false);
2552                 if (ret < 0)
2553                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2554         }
2555         /*
2556          * If this command is not a write we can execute it right here,
2557          * for write buffers we need to notify the fabric driver first
2558          * and let it call back once the write buffers are ready.
2559          */
2560         target_add_to_state_list(cmd);
2561         if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2562                 target_execute_cmd(cmd);
2563                 return 0;
2564         }
2565
2566         spin_lock_irqsave(&cmd->t_state_lock, flags);
2567         cmd->t_state = TRANSPORT_WRITE_PENDING;
2568         /*
2569          * Determine if frontend context caller is requesting the stopping of
2570          * this command for frontend exceptions.
2571          */
2572         if (cmd->transport_state & CMD_T_STOP) {
2573                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2574                          __func__, __LINE__, cmd->tag);
2575
2576                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2577
2578                 complete_all(&cmd->t_transport_stop_comp);
2579                 return 0;
2580         }
2581         cmd->transport_state &= ~CMD_T_ACTIVE;
2582         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2583
2584         ret = cmd->se_tfo->write_pending(cmd);
2585         if (ret)
2586                 goto queue_full;
2587
2588         return 0;
2589
2590 queue_full:
2591         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2592         transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2593         return 0;
2594 }
2595 EXPORT_SYMBOL(transport_generic_new_cmd);
2596
2597 static void transport_write_pending_qf(struct se_cmd *cmd)
2598 {
2599         unsigned long flags;
2600         int ret;
2601         bool stop;
2602
2603         spin_lock_irqsave(&cmd->t_state_lock, flags);
2604         stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2605         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2606
2607         if (stop) {
2608                 pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2609                         __func__, __LINE__, cmd->tag);
2610                 complete_all(&cmd->t_transport_stop_comp);
2611                 return;
2612         }
2613
2614         ret = cmd->se_tfo->write_pending(cmd);
2615         if (ret) {
2616                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2617                          cmd);
2618                 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2619         }
2620 }
2621
2622 static bool
2623 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2624                            unsigned long *flags);
2625
2626 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2627 {
2628         unsigned long flags;
2629
2630         spin_lock_irqsave(&cmd->t_state_lock, flags);
2631         __transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2632         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2633 }
2634
2635 /*
2636  * This function is called by frontend drivers after processing of a command
2637  * has finished.
2638  *
2639  * The protocol for ensuring that either the regular flow or the TMF
2640  * code drops one reference is as follows:
2641  * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2642  *   the frontend driver to drop one reference, synchronously or asynchronously.
2643  * - During regular command processing the target core sets CMD_T_COMPLETE
2644  *   before invoking one of the .queue_*() functions.
2645  * - The code that aborts commands skips commands and TMFs for which
2646  *   CMD_T_COMPLETE has been set.
2647  * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2648  *   commands that will be aborted.
2649  * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2650  *   transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2651  * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2652  *   be called and will drop a reference.
2653  * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2654  *   will be called. transport_cmd_finish_abort() will drop the final reference.
2655  */
2656 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2657 {
2658         DECLARE_COMPLETION_ONSTACK(compl);
2659         int ret = 0;
2660         bool aborted = false, tas = false;
2661
2662         if (wait_for_tasks)
2663                 target_wait_free_cmd(cmd, &aborted, &tas);
2664
2665         if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2666                 /*
2667                  * Handle WRITE failure case where transport_generic_new_cmd()
2668                  * has already added se_cmd to state_list, but fabric has
2669                  * failed command before I/O submission.
2670                  */
2671                 if (cmd->state_active)
2672                         target_remove_from_state_list(cmd);
2673
2674                 if (cmd->se_lun)
2675                         transport_lun_remove_cmd(cmd);
2676         }
2677         if (aborted)
2678                 cmd->compl = &compl;
2679         if (!aborted || tas)
2680                 ret = target_put_sess_cmd(cmd);
2681         if (aborted) {
2682                 pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2683                 wait_for_completion(&compl);
2684                 ret = 1;
2685         }
2686         return ret;
2687 }
2688 EXPORT_SYMBOL(transport_generic_free_cmd);
2689
2690 /**
2691  * target_get_sess_cmd - Add command to active ->sess_cmd_list
2692  * @se_cmd:     command descriptor to add
2693  * @ack_kref:   Signal that fabric will perform an ack target_put_sess_cmd()
2694  */
2695 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2696 {
2697         struct se_session *se_sess = se_cmd->se_sess;
2698         unsigned long flags;
2699         int ret = 0;
2700
2701         /*
2702          * Add a second kref if the fabric caller is expecting to handle
2703          * fabric acknowledgement that requires two target_put_sess_cmd()
2704          * invocations before se_cmd descriptor release.
2705          */
2706         if (ack_kref) {
2707                 if (!kref_get_unless_zero(&se_cmd->cmd_kref))
2708                         return -EINVAL;
2709
2710                 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2711         }
2712
2713         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2714         if (se_sess->sess_tearing_down) {
2715                 ret = -ESHUTDOWN;
2716                 goto out;
2717         }
2718         se_cmd->transport_state |= CMD_T_PRE_EXECUTE;
2719         list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2720 out:
2721         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2722
2723         if (ret && ack_kref)
2724                 target_put_sess_cmd(se_cmd);
2725
2726         return ret;
2727 }
2728 EXPORT_SYMBOL(target_get_sess_cmd);
2729
2730 static void target_free_cmd_mem(struct se_cmd *cmd)
2731 {
2732         transport_free_pages(cmd);
2733
2734         if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2735                 core_tmr_release_req(cmd->se_tmr_req);
2736         if (cmd->t_task_cdb != cmd->__t_task_cdb)
2737                 kfree(cmd->t_task_cdb);
2738 }
2739
2740 static void target_release_cmd_kref(struct kref *kref)
2741 {
2742         struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2743         struct se_session *se_sess = se_cmd->se_sess;
2744         struct completion *compl = se_cmd->compl;
2745         unsigned long flags;
2746
2747         if (se_sess) {
2748                 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2749                 list_del_init(&se_cmd->se_cmd_list);
2750                 if (list_empty(&se_sess->sess_cmd_list))
2751                         wake_up(&se_sess->cmd_list_wq);
2752                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2753         }
2754
2755         target_free_cmd_mem(se_cmd);
2756         se_cmd->se_tfo->release_cmd(se_cmd);
2757         if (compl)
2758                 complete(compl);
2759 }
2760
2761 /**
2762  * target_put_sess_cmd - decrease the command reference count
2763  * @se_cmd:     command to drop a reference from
2764  *
2765  * Returns 1 if and only if this target_put_sess_cmd() call caused the
2766  * refcount to drop to zero. Returns zero otherwise.
2767  */
2768 int target_put_sess_cmd(struct se_cmd *se_cmd)
2769 {
2770         return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2771 }
2772 EXPORT_SYMBOL(target_put_sess_cmd);
2773
2774 static const char *data_dir_name(enum dma_data_direction d)
2775 {
2776         switch (d) {
2777         case DMA_BIDIRECTIONAL: return "BIDI";
2778         case DMA_TO_DEVICE:     return "WRITE";
2779         case DMA_FROM_DEVICE:   return "READ";
2780         case DMA_NONE:          return "NONE";
2781         }
2782
2783         return "(?)";
2784 }
2785
2786 static const char *cmd_state_name(enum transport_state_table t)
2787 {
2788         switch (t) {
2789         case TRANSPORT_NO_STATE:        return "NO_STATE";
2790         case TRANSPORT_NEW_CMD:         return "NEW_CMD";
2791         case TRANSPORT_WRITE_PENDING:   return "WRITE_PENDING";
2792         case TRANSPORT_PROCESSING:      return "PROCESSING";
2793         case TRANSPORT_COMPLETE:        return "COMPLETE";
2794         case TRANSPORT_ISTATE_PROCESSING:
2795                                         return "ISTATE_PROCESSING";
2796         case TRANSPORT_COMPLETE_QF_WP:  return "COMPLETE_QF_WP";
2797         case TRANSPORT_COMPLETE_QF_OK:  return "COMPLETE_QF_OK";
2798         case TRANSPORT_COMPLETE_QF_ERR: return "COMPLETE_QF_ERR";
2799         }
2800
2801         return "(?)";
2802 }
2803
2804 static void target_append_str(char **str, const char *txt)
2805 {
2806         char *prev = *str;
2807
2808         *str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
2809                 kstrdup(txt, GFP_ATOMIC);
2810         kfree(prev);
2811 }
2812
2813 /*
2814  * Convert a transport state bitmask into a string. The caller is
2815  * responsible for freeing the returned pointer.
2816  */
2817 static char *target_ts_to_str(u32 ts)
2818 {
2819         char *str = NULL;
2820
2821         if (ts & CMD_T_ABORTED)
2822                 target_append_str(&str, "aborted");
2823         if (ts & CMD_T_ACTIVE)
2824                 target_append_str(&str, "active");
2825         if (ts & CMD_T_COMPLETE)
2826                 target_append_str(&str, "complete");
2827         if (ts & CMD_T_SENT)
2828                 target_append_str(&str, "sent");
2829         if (ts & CMD_T_STOP)
2830                 target_append_str(&str, "stop");
2831         if (ts & CMD_T_FABRIC_STOP)
2832                 target_append_str(&str, "fabric_stop");
2833
2834         return str;
2835 }
2836
2837 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
2838 {
2839         switch (tmf) {
2840         case TMR_ABORT_TASK:            return "ABORT_TASK";
2841         case TMR_ABORT_TASK_SET:        return "ABORT_TASK_SET";
2842         case TMR_CLEAR_ACA:             return "CLEAR_ACA";
2843         case TMR_CLEAR_TASK_SET:        return "CLEAR_TASK_SET";
2844         case TMR_LUN_RESET:             return "LUN_RESET";
2845         case TMR_TARGET_WARM_RESET:     return "TARGET_WARM_RESET";
2846         case TMR_TARGET_COLD_RESET:     return "TARGET_COLD_RESET";
2847         case TMR_UNKNOWN:               break;
2848         }
2849         return "(?)";
2850 }
2851
2852 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
2853 {
2854         char *ts_str = target_ts_to_str(cmd->transport_state);
2855         const u8 *cdb = cmd->t_task_cdb;
2856         struct se_tmr_req *tmf = cmd->se_tmr_req;
2857
2858         if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2859                 pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
2860                          pfx, cdb[0], cdb[1], cmd->tag,
2861                          data_dir_name(cmd->data_direction),
2862                          cmd->se_tfo->get_cmd_state(cmd),
2863                          cmd_state_name(cmd->t_state), cmd->data_length,
2864                          kref_read(&cmd->cmd_kref), ts_str);
2865         } else {
2866                 pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
2867                          pfx, target_tmf_name(tmf->function), cmd->tag,
2868                          tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
2869                          cmd_state_name(cmd->t_state),
2870                          kref_read(&cmd->cmd_kref), ts_str);
2871         }
2872         kfree(ts_str);
2873 }
2874 EXPORT_SYMBOL(target_show_cmd);
2875
2876 /**
2877  * target_sess_cmd_list_set_waiting - Set sess_tearing_down so no new commands are queued.
2878  * @se_sess:    session to flag
2879  */
2880 void target_sess_cmd_list_set_waiting(struct se_session *se_sess)
2881 {
2882         unsigned long flags;
2883
2884         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2885         se_sess->sess_tearing_down = 1;
2886         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2887 }
2888 EXPORT_SYMBOL(target_sess_cmd_list_set_waiting);
2889
2890 /**
2891  * target_wait_for_sess_cmds - Wait for outstanding commands
2892  * @se_sess:    session to wait for active I/O
2893  */
2894 void target_wait_for_sess_cmds(struct se_session *se_sess)
2895 {
2896         struct se_cmd *cmd;
2897         int ret;
2898
2899         WARN_ON_ONCE(!se_sess->sess_tearing_down);
2900
2901         spin_lock_irq(&se_sess->sess_cmd_lock);
2902         do {
2903                 ret = wait_event_interruptible_lock_irq_timeout(
2904                                 se_sess->cmd_list_wq,
2905                                 list_empty(&se_sess->sess_cmd_list),
2906                                 se_sess->sess_cmd_lock, 180 * HZ);
2907                 list_for_each_entry(cmd, &se_sess->sess_cmd_list, se_cmd_list)
2908                         target_show_cmd("session shutdown: still waiting for ",
2909                                         cmd);
2910         } while (ret <= 0);
2911         spin_unlock_irq(&se_sess->sess_cmd_lock);
2912 }
2913 EXPORT_SYMBOL(target_wait_for_sess_cmds);
2914
2915 static void target_lun_confirm(struct percpu_ref *ref)
2916 {
2917         struct se_lun *lun = container_of(ref, struct se_lun, lun_ref);
2918
2919         complete(&lun->lun_ref_comp);
2920 }
2921
2922 void transport_clear_lun_ref(struct se_lun *lun)
2923 {
2924         /*
2925          * Mark the percpu-ref as DEAD, switch to atomic_t mode, drop
2926          * the initial reference and schedule confirm kill to be
2927          * executed after one full RCU grace period has completed.
2928          */
2929         percpu_ref_kill_and_confirm(&lun->lun_ref, target_lun_confirm);
2930         /*
2931          * The first completion waits for percpu_ref_switch_to_atomic_rcu()
2932          * to call target_lun_confirm after lun->lun_ref has been marked
2933          * as __PERCPU_REF_DEAD on all CPUs, and switches to atomic_t
2934          * mode so that percpu_ref_tryget_live() lookup of lun->lun_ref
2935          * fails for all new incoming I/O.
2936          */
2937         wait_for_completion(&lun->lun_ref_comp);
2938         /*
2939          * The second completion waits for percpu_ref_put_many() to
2940          * invoke ->release() after lun->lun_ref has switched to
2941          * atomic_t mode, and lun->lun_ref.count has reached zero.
2942          *
2943          * At this point all target-core lun->lun_ref references have
2944          * been dropped via transport_lun_remove_cmd(), and it's safe
2945          * to proceed with the remaining LUN shutdown.
2946          */
2947         wait_for_completion(&lun->lun_shutdown_comp);
2948 }
2949
2950 static bool
2951 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
2952                            bool *aborted, bool *tas, unsigned long *flags)
2953         __releases(&cmd->t_state_lock)
2954         __acquires(&cmd->t_state_lock)
2955 {
2956
2957         assert_spin_locked(&cmd->t_state_lock);
2958         WARN_ON_ONCE(!irqs_disabled());
2959
2960         if (fabric_stop)
2961                 cmd->transport_state |= CMD_T_FABRIC_STOP;
2962
2963         if (cmd->transport_state & CMD_T_ABORTED)
2964                 *aborted = true;
2965
2966         if (cmd->transport_state & CMD_T_TAS)
2967                 *tas = true;
2968
2969         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
2970             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2971                 return false;
2972
2973         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
2974             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2975                 return false;
2976
2977         if (!(cmd->transport_state & CMD_T_ACTIVE))
2978                 return false;
2979
2980         if (fabric_stop && *aborted)
2981                 return false;
2982
2983         cmd->transport_state |= CMD_T_STOP;
2984
2985         target_show_cmd("wait_for_tasks: Stopping ", cmd);
2986
2987         spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
2988
2989         while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
2990                                             180 * HZ))
2991                 target_show_cmd("wait for tasks: ", cmd);
2992
2993         spin_lock_irqsave(&cmd->t_state_lock, *flags);
2994         cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
2995
2996         pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
2997                  "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
2998
2999         return true;
3000 }
3001
3002 /**
3003  * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3004  * @cmd: command to wait on
3005  */
3006 bool transport_wait_for_tasks(struct se_cmd *cmd)
3007 {
3008         unsigned long flags;
3009         bool ret, aborted = false, tas = false;
3010
3011         spin_lock_irqsave(&cmd->t_state_lock, flags);
3012         ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3013         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3014
3015         return ret;
3016 }
3017 EXPORT_SYMBOL(transport_wait_for_tasks);
3018
3019 struct sense_info {
3020         u8 key;
3021         u8 asc;
3022         u8 ascq;
3023         bool add_sector_info;
3024 };
3025
3026 static const struct sense_info sense_info_table[] = {
3027         [TCM_NO_SENSE] = {
3028                 .key = NOT_READY
3029         },
3030         [TCM_NON_EXISTENT_LUN] = {
3031                 .key = ILLEGAL_REQUEST,
3032                 .asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3033         },
3034         [TCM_UNSUPPORTED_SCSI_OPCODE] = {
3035                 .key = ILLEGAL_REQUEST,
3036                 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3037         },
3038         [TCM_SECTOR_COUNT_TOO_MANY] = {
3039                 .key = ILLEGAL_REQUEST,
3040                 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3041         },
3042         [TCM_UNKNOWN_MODE_PAGE] = {
3043                 .key = ILLEGAL_REQUEST,
3044                 .asc = 0x24, /* INVALID FIELD IN CDB */
3045         },
3046         [TCM_CHECK_CONDITION_ABORT_CMD] = {
3047                 .key = ABORTED_COMMAND,
3048                 .asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3049                 .ascq = 0x03,
3050         },
3051         [TCM_INCORRECT_AMOUNT_OF_DATA] = {
3052                 .key = ABORTED_COMMAND,
3053                 .asc = 0x0c, /* WRITE ERROR */
3054                 .ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3055         },
3056         [TCM_INVALID_CDB_FIELD] = {
3057                 .key = ILLEGAL_REQUEST,
3058                 .asc = 0x24, /* INVALID FIELD IN CDB */
3059         },
3060         [TCM_INVALID_PARAMETER_LIST] = {
3061                 .key = ILLEGAL_REQUEST,
3062                 .asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3063         },
3064         [TCM_TOO_MANY_TARGET_DESCS] = {
3065                 .key = ILLEGAL_REQUEST,
3066                 .asc = 0x26,
3067                 .ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3068         },
3069         [TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3070                 .key = ILLEGAL_REQUEST,
3071                 .asc = 0x26,
3072                 .ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3073         },
3074         [TCM_TOO_MANY_SEGMENT_DESCS] = {
3075                 .key = ILLEGAL_REQUEST,
3076                 .asc = 0x26,
3077                 .ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3078         },
3079         [TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3080                 .key = ILLEGAL_REQUEST,
3081                 .asc = 0x26,
3082                 .ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3083         },
3084         [TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3085                 .key = ILLEGAL_REQUEST,
3086                 .asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3087         },
3088         [TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3089                 .key = ILLEGAL_REQUEST,
3090                 .asc = 0x0c, /* WRITE ERROR */
3091                 .ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3092         },
3093         [TCM_SERVICE_CRC_ERROR] = {
3094                 .key = ABORTED_COMMAND,
3095                 .asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3096                 .ascq = 0x05, /* N/A */
3097         },
3098         [TCM_SNACK_REJECTED] = {
3099                 .key = ABORTED_COMMAND,
3100                 .asc = 0x11, /* READ ERROR */
3101                 .ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3102         },
3103         [TCM_WRITE_PROTECTED] = {
3104                 .key = DATA_PROTECT,
3105                 .asc = 0x27, /* WRITE PROTECTED */
3106         },
3107         [TCM_ADDRESS_OUT_OF_RANGE] = {
3108                 .key = ILLEGAL_REQUEST,
3109                 .asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3110         },
3111         [TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3112                 .key = UNIT_ATTENTION,
3113         },
3114         [TCM_CHECK_CONDITION_NOT_READY] = {
3115                 .key = NOT_READY,
3116         },
3117         [TCM_MISCOMPARE_VERIFY] = {
3118                 .key = MISCOMPARE,
3119                 .asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3120                 .ascq = 0x00,
3121         },
3122         [TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3123                 .key = ABORTED_COMMAND,
3124                 .asc = 0x10,
3125                 .ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3126                 .add_sector_info = true,
3127         },
3128         [TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3129                 .key = ABORTED_COMMAND,
3130                 .asc = 0x10,
3131                 .ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3132                 .add_sector_info = true,
3133         },
3134         [TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3135                 .key = ABORTED_COMMAND,
3136                 .asc = 0x10,
3137                 .ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3138                 .add_sector_info = true,
3139         },
3140         [TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3141                 .key = COPY_ABORTED,
3142                 .asc = 0x0d,
3143                 .ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3144
3145         },
3146         [TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3147                 /*
3148                  * Returning ILLEGAL REQUEST would cause immediate IO errors on
3149                  * Solaris initiators.  Returning NOT READY instead means the
3150                  * operations will be retried a finite number of times and we
3151                  * can survive intermittent errors.
3152                  */
3153                 .key = NOT_READY,
3154                 .asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3155         },
3156         [TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3157                 /*
3158                  * From spc4r22 section5.7.7,5.7.8
3159                  * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3160                  * or a REGISTER AND IGNORE EXISTING KEY service action or
3161                  * REGISTER AND MOVE service actionis attempted,
3162                  * but there are insufficient device server resources to complete the
3163                  * operation, then the command shall be terminated with CHECK CONDITION
3164                  * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3165                  * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3166                  */
3167                 .key = ILLEGAL_REQUEST,
3168                 .asc = 0x55,
3169                 .ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3170         },
3171 };
3172
3173 /**
3174  * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3175  * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3176  *   be stored.
3177  * @reason: LIO sense reason code. If this argument has the value
3178  *   TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3179  *   dequeuing a unit attention fails due to multiple commands being processed
3180  *   concurrently, set the command status to BUSY.
3181  *
3182  * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3183  */
3184 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3185 {
3186         const struct sense_info *si;
3187         u8 *buffer = cmd->sense_buffer;
3188         int r = (__force int)reason;
3189         u8 key, asc, ascq;
3190         bool desc_format = target_sense_desc_format(cmd->se_dev);
3191
3192         if (r < ARRAY_SIZE(sense_info_table) && sense_info_table[r].key)
3193                 si = &sense_info_table[r];
3194         else
3195                 si = &sense_info_table[(__force int)
3196                                        TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3197
3198         key = si->key;
3199         if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3200                 if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3201                                                        &ascq)) {
3202                         cmd->scsi_status = SAM_STAT_BUSY;
3203                         return;
3204                 }
3205         } else if (si->asc == 0) {
3206                 WARN_ON_ONCE(cmd->scsi_asc == 0);
3207                 asc = cmd->scsi_asc;
3208                 ascq = cmd->scsi_ascq;
3209         } else {
3210                 asc = si->asc;
3211                 ascq = si->ascq;
3212         }
3213
3214         cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3215         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3216         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER;
3217         scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3218         if (si->add_sector_info)
3219                 WARN_ON_ONCE(scsi_set_sense_information(buffer,
3220                                                         cmd->scsi_sense_length,
3221                                                         cmd->bad_sector) < 0);
3222 }
3223
3224 int
3225 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3226                 sense_reason_t reason, int from_transport)
3227 {
3228         unsigned long flags;
3229
3230         spin_lock_irqsave(&cmd->t_state_lock, flags);
3231         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3232                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3233                 return 0;
3234         }
3235         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3236         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3237
3238         if (!from_transport)
3239                 translate_sense_reason(cmd, reason);
3240
3241         trace_target_cmd_complete(cmd);
3242         return cmd->se_tfo->queue_status(cmd);
3243 }
3244 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3245
3246 static int __transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3247         __releases(&cmd->t_state_lock)
3248         __acquires(&cmd->t_state_lock)
3249 {
3250         int ret;
3251
3252         assert_spin_locked(&cmd->t_state_lock);
3253         WARN_ON_ONCE(!irqs_disabled());
3254
3255         if (!(cmd->transport_state & CMD_T_ABORTED))
3256                 return 0;
3257         /*
3258          * If cmd has been aborted but either no status is to be sent or it has
3259          * already been sent, just return
3260          */
3261         if (!send_status || !(cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS)) {
3262                 if (send_status)
3263                         cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS;
3264                 return 1;
3265         }
3266
3267         pr_debug("Sending delayed SAM_STAT_TASK_ABORTED status for CDB:"
3268                 " 0x%02x ITT: 0x%08llx\n", cmd->t_task_cdb[0], cmd->tag);
3269
3270         cmd->se_cmd_flags &= ~SCF_SEND_DELAYED_TAS;
3271         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3272         trace_target_cmd_complete(cmd);
3273
3274         spin_unlock_irq(&cmd->t_state_lock);
3275         ret = cmd->se_tfo->queue_status(cmd);
3276         if (ret)
3277                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
3278         spin_lock_irq(&cmd->t_state_lock);
3279
3280         return 1;
3281 }
3282
3283 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3284 {
3285         int ret;
3286
3287         spin_lock_irq(&cmd->t_state_lock);
3288         ret = __transport_check_aborted_status(cmd, send_status);
3289         spin_unlock_irq(&cmd->t_state_lock);
3290
3291         return ret;
3292 }
3293 EXPORT_SYMBOL(transport_check_aborted_status);
3294
3295 void transport_send_task_abort(struct se_cmd *cmd)
3296 {
3297         unsigned long flags;
3298         int ret;
3299
3300         spin_lock_irqsave(&cmd->t_state_lock, flags);
3301         if (cmd->se_cmd_flags & (SCF_SENT_CHECK_CONDITION)) {
3302                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3303                 return;
3304         }
3305         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3306
3307         /*
3308          * If there are still expected incoming fabric WRITEs, we wait
3309          * until until they have completed before sending a TASK_ABORTED
3310          * response.  This response with TASK_ABORTED status will be
3311          * queued back to fabric module by transport_check_aborted_status().
3312          */
3313         if (cmd->data_direction == DMA_TO_DEVICE) {
3314                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
3315                         spin_lock_irqsave(&cmd->t_state_lock, flags);
3316                         if (cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS) {
3317                                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3318                                 goto send_abort;
3319                         }
3320                         cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS;
3321                         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3322                         return;
3323                 }
3324         }
3325 send_abort:
3326         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3327
3328         transport_lun_remove_cmd(cmd);
3329
3330         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
3331                  cmd->t_task_cdb[0], cmd->tag);
3332
3333         trace_target_cmd_complete(cmd);
3334         ret = cmd->se_tfo->queue_status(cmd);
3335         if (ret)
3336                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
3337 }
3338
3339 static void target_tmr_work(struct work_struct *work)
3340 {
3341         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3342         struct se_device *dev = cmd->se_dev;
3343         struct se_tmr_req *tmr = cmd->se_tmr_req;
3344         unsigned long flags;
3345         int ret;
3346
3347         spin_lock_irqsave(&cmd->t_state_lock, flags);
3348         if (cmd->transport_state & CMD_T_ABORTED) {
3349                 tmr->response = TMR_FUNCTION_REJECTED;
3350                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3351                 goto check_stop;
3352         }
3353         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3354
3355         switch (tmr->function) {
3356         case TMR_ABORT_TASK:
3357                 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3358                 break;
3359         case TMR_ABORT_TASK_SET:
3360         case TMR_CLEAR_ACA:
3361         case TMR_CLEAR_TASK_SET:
3362                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3363                 break;
3364         case TMR_LUN_RESET:
3365                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3366                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3367                                          TMR_FUNCTION_REJECTED;
3368                 if (tmr->response == TMR_FUNCTION_COMPLETE) {
3369                         target_ua_allocate_lun(cmd->se_sess->se_node_acl,
3370                                                cmd->orig_fe_lun, 0x29,
3371                                                ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3372                 }
3373                 break;
3374         case TMR_TARGET_WARM_RESET:
3375                 tmr->response = TMR_FUNCTION_REJECTED;
3376                 break;
3377         case TMR_TARGET_COLD_RESET:
3378                 tmr->response = TMR_FUNCTION_REJECTED;
3379                 break;
3380         default:
3381                 pr_err("Unknown TMR function: 0x%02x.\n",
3382                                 tmr->function);
3383                 tmr->response = TMR_FUNCTION_REJECTED;
3384                 break;
3385         }
3386
3387         spin_lock_irqsave(&cmd->t_state_lock, flags);
3388         if (cmd->transport_state & CMD_T_ABORTED) {
3389                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3390                 goto check_stop;
3391         }
3392         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3393
3394         cmd->se_tfo->queue_tm_rsp(cmd);
3395
3396 check_stop:
3397         transport_lun_remove_cmd(cmd);
3398         transport_cmd_check_stop_to_fabric(cmd);
3399 }
3400
3401 int transport_generic_handle_tmr(
3402         struct se_cmd *cmd)
3403 {
3404         unsigned long flags;
3405         bool aborted = false;
3406
3407         spin_lock_irqsave(&cmd->t_state_lock, flags);
3408         if (cmd->transport_state & CMD_T_ABORTED) {
3409                 aborted = true;
3410         } else {
3411                 cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3412                 cmd->transport_state |= CMD_T_ACTIVE;
3413         }
3414         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3415
3416         if (aborted) {
3417                 pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d"
3418                         "ref_tag: %llu tag: %llu\n", cmd->se_tmr_req->function,
3419                         cmd->se_tmr_req->ref_task_tag, cmd->tag);
3420                 transport_lun_remove_cmd(cmd);
3421                 transport_cmd_check_stop_to_fabric(cmd);
3422                 return 0;
3423         }
3424
3425         INIT_WORK(&cmd->work, target_tmr_work);
3426         queue_work(cmd->se_dev->tmr_wq, &cmd->work);
3427         return 0;
3428 }
3429 EXPORT_SYMBOL(transport_generic_handle_tmr);
3430
3431 bool
3432 target_check_wce(struct se_device *dev)
3433 {
3434         bool wce = false;
3435
3436         if (dev->transport->get_write_cache)
3437                 wce = dev->transport->get_write_cache(dev);
3438         else if (dev->dev_attrib.emulate_write_cache > 0)
3439                 wce = true;
3440
3441         return wce;
3442 }
3443
3444 bool
3445 target_check_fua(struct se_device *dev)
3446 {
3447         return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;
3448 }