[SCSI] libiscsi: have iscsi_data_in_rsp call iscsi_update_cmdsn
[linux-2.6.git] / drivers / scsi / libiscsi.c
1 /*
2  * iSCSI lib functions
3  *
4  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
5  * Copyright (C) 2004 - 2006 Mike Christie
6  * Copyright (C) 2004 - 2005 Dmitry Yusupov
7  * Copyright (C) 2004 - 2005 Alex Aizman
8  * maintained by open-iscsi@googlegroups.com
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 #include <linux/types.h>
25 #include <linux/kfifo.h>
26 #include <linux/delay.h>
27 #include <linux/log2.h>
28 #include <asm/unaligned.h>
29 #include <net/tcp.h>
30 #include <scsi/scsi_cmnd.h>
31 #include <scsi/scsi_device.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_tcq.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi.h>
36 #include <scsi/iscsi_proto.h>
37 #include <scsi/scsi_transport.h>
38 #include <scsi/scsi_transport_iscsi.h>
39 #include <scsi/libiscsi.h>
40
41 static int iscsi_dbg_lib;
42 module_param_named(debug_libiscsi, iscsi_dbg_lib, int, S_IRUGO | S_IWUSR);
43 MODULE_PARM_DESC(debug_libiscsi, "Turn on debugging for libiscsi module. "
44                  "Set to 1 to turn on, and zero to turn off. Default "
45                  "is off.");
46
47 #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...)                  \
48         do {                                                    \
49                 if (iscsi_dbg_lib)                              \
50                         iscsi_conn_printk(KERN_INFO, _conn,     \
51                                              "%s " dbg_fmt,     \
52                                              __func__, ##arg);  \
53         } while (0);
54
55 #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...)                    \
56         do {                                                            \
57                 if (iscsi_dbg_lib)                                      \
58                         iscsi_session_printk(KERN_INFO, _session,       \
59                                              "%s " dbg_fmt,             \
60                                              __func__, ##arg);          \
61         } while (0);
62
63 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
64 #define SNA32_CHECK 2147483648UL
65
66 static int iscsi_sna_lt(u32 n1, u32 n2)
67 {
68         return n1 != n2 && ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
69                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
70 }
71
72 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
73 static int iscsi_sna_lte(u32 n1, u32 n2)
74 {
75         return n1 == n2 || ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
76                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
77 }
78
79 inline void iscsi_conn_queue_work(struct iscsi_conn *conn)
80 {
81         struct Scsi_Host *shost = conn->session->host;
82         struct iscsi_host *ihost = shost_priv(shost);
83
84         queue_work(ihost->workq, &conn->xmitwork);
85 }
86 EXPORT_SYMBOL_GPL(iscsi_conn_queue_work);
87
88 void
89 iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
90 {
91         uint32_t max_cmdsn = be32_to_cpu(hdr->max_cmdsn);
92         uint32_t exp_cmdsn = be32_to_cpu(hdr->exp_cmdsn);
93
94         /*
95          * standard specifies this check for when to update expected and
96          * max sequence numbers
97          */
98         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
99                 return;
100
101         if (exp_cmdsn != session->exp_cmdsn &&
102             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
103                 session->exp_cmdsn = exp_cmdsn;
104
105         if (max_cmdsn != session->max_cmdsn &&
106             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) {
107                 session->max_cmdsn = max_cmdsn;
108                 /*
109                  * if the window closed with IO queued, then kick the
110                  * xmit thread
111                  */
112                 if (!list_empty(&session->leadconn->xmitqueue) ||
113                     !list_empty(&session->leadconn->mgmtqueue)) {
114                         if (!(session->tt->caps & CAP_DATA_PATH_OFFLOAD))
115                                 iscsi_conn_queue_work(session->leadconn);
116                 }
117         }
118 }
119 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
120
121 /**
122  * iscsi_prep_data_out_pdu - initialize Data-Out
123  * @task: scsi command task
124  * @r2t: R2T info
125  * @hdr: iscsi data in pdu
126  *
127  * Notes:
128  *      Initialize Data-Out within this R2T sequence and finds
129  *      proper data_offset within this SCSI command.
130  *
131  *      This function is called with connection lock taken.
132  **/
133 void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t,
134                            struct iscsi_data *hdr)
135 {
136         struct iscsi_conn *conn = task->conn;
137         unsigned int left = r2t->data_length - r2t->sent;
138
139         task->hdr_len = sizeof(struct iscsi_data);
140
141         memset(hdr, 0, sizeof(struct iscsi_data));
142         hdr->ttt = r2t->ttt;
143         hdr->datasn = cpu_to_be32(r2t->datasn);
144         r2t->datasn++;
145         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
146         memcpy(hdr->lun, task->lun, sizeof(hdr->lun));
147         hdr->itt = task->hdr_itt;
148         hdr->exp_statsn = r2t->exp_statsn;
149         hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent);
150         if (left > conn->max_xmit_dlength) {
151                 hton24(hdr->dlength, conn->max_xmit_dlength);
152                 r2t->data_count = conn->max_xmit_dlength;
153                 hdr->flags = 0;
154         } else {
155                 hton24(hdr->dlength, left);
156                 r2t->data_count = left;
157                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
158         }
159         conn->dataout_pdus_cnt++;
160 }
161 EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu);
162
163 static int iscsi_add_hdr(struct iscsi_task *task, unsigned len)
164 {
165         unsigned exp_len = task->hdr_len + len;
166
167         if (exp_len > task->hdr_max) {
168                 WARN_ON(1);
169                 return -EINVAL;
170         }
171
172         WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
173         task->hdr_len = exp_len;
174         return 0;
175 }
176
177 /*
178  * make an extended cdb AHS
179  */
180 static int iscsi_prep_ecdb_ahs(struct iscsi_task *task)
181 {
182         struct scsi_cmnd *cmd = task->sc;
183         unsigned rlen, pad_len;
184         unsigned short ahslength;
185         struct iscsi_ecdb_ahdr *ecdb_ahdr;
186         int rc;
187
188         ecdb_ahdr = iscsi_next_hdr(task);
189         rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
190
191         BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
192         ahslength = rlen + sizeof(ecdb_ahdr->reserved);
193
194         pad_len = iscsi_padding(rlen);
195
196         rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) +
197                            sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
198         if (rc)
199                 return rc;
200
201         if (pad_len)
202                 memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
203
204         ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
205         ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
206         ecdb_ahdr->reserved = 0;
207         memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
208
209         ISCSI_DBG_SESSION(task->conn->session,
210                           "iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
211                           "rlen %d pad_len %d ahs_length %d iscsi_headers_size "
212                           "%u\n", cmd->cmd_len, rlen, pad_len, ahslength,
213                           task->hdr_len);
214         return 0;
215 }
216
217 static int iscsi_prep_bidi_ahs(struct iscsi_task *task)
218 {
219         struct scsi_cmnd *sc = task->sc;
220         struct iscsi_rlength_ahdr *rlen_ahdr;
221         int rc;
222
223         rlen_ahdr = iscsi_next_hdr(task);
224         rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr));
225         if (rc)
226                 return rc;
227
228         rlen_ahdr->ahslength =
229                 cpu_to_be16(sizeof(rlen_ahdr->read_length) +
230                                                   sizeof(rlen_ahdr->reserved));
231         rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH;
232         rlen_ahdr->reserved = 0;
233         rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length);
234
235         ISCSI_DBG_SESSION(task->conn->session,
236                           "bidi-in rlen_ahdr->read_length(%d) "
237                           "rlen_ahdr->ahslength(%d)\n",
238                           be32_to_cpu(rlen_ahdr->read_length),
239                           be16_to_cpu(rlen_ahdr->ahslength));
240         return 0;
241 }
242
243 /**
244  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
245  * @task: iscsi task
246  *
247  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
248  * fields like dlength or final based on how much data it sends
249  */
250 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task)
251 {
252         struct iscsi_conn *conn = task->conn;
253         struct iscsi_session *session = conn->session;
254         struct scsi_cmnd *sc = task->sc;
255         struct iscsi_cmd *hdr;
256         unsigned hdrlength, cmd_len;
257         itt_t itt;
258         int rc;
259
260         if (conn->session->tt->alloc_pdu) {
261                 rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD);
262                 if (rc)
263                         return rc;
264         }
265         hdr = (struct iscsi_cmd *) task->hdr;
266         itt = hdr->itt;
267         memset(hdr, 0, sizeof(*hdr));
268
269         if (session->tt->parse_pdu_itt)
270                 hdr->itt = task->hdr_itt = itt;
271         else
272                 hdr->itt = task->hdr_itt = build_itt(task->itt,
273                                                      task->conn->session->age);
274         task->hdr_len = 0;
275         rc = iscsi_add_hdr(task, sizeof(*hdr));
276         if (rc)
277                 return rc;
278         hdr->opcode = ISCSI_OP_SCSI_CMD;
279         hdr->flags = ISCSI_ATTR_SIMPLE;
280         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
281         memcpy(task->lun, hdr->lun, sizeof(task->lun));
282         hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn);
283         session->cmdsn++;
284         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
285         cmd_len = sc->cmd_len;
286         if (cmd_len < ISCSI_CDB_SIZE)
287                 memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
288         else if (cmd_len > ISCSI_CDB_SIZE) {
289                 rc = iscsi_prep_ecdb_ahs(task);
290                 if (rc)
291                         return rc;
292                 cmd_len = ISCSI_CDB_SIZE;
293         }
294         memcpy(hdr->cdb, sc->cmnd, cmd_len);
295
296         task->imm_count = 0;
297         if (scsi_bidi_cmnd(sc)) {
298                 hdr->flags |= ISCSI_FLAG_CMD_READ;
299                 rc = iscsi_prep_bidi_ahs(task);
300                 if (rc)
301                         return rc;
302         }
303         if (sc->sc_data_direction == DMA_TO_DEVICE) {
304                 unsigned out_len = scsi_out(sc)->length;
305                 struct iscsi_r2t_info *r2t = &task->unsol_r2t;
306
307                 hdr->data_length = cpu_to_be32(out_len);
308                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
309                 /*
310                  * Write counters:
311                  *
312                  *      imm_count       bytes to be sent right after
313                  *                      SCSI PDU Header
314                  *
315                  *      unsol_count     bytes(as Data-Out) to be sent
316                  *                      without R2T ack right after
317                  *                      immediate data
318                  *
319                  *      r2t data_length bytes to be sent via R2T ack's
320                  *
321                  *      pad_count       bytes to be sent as zero-padding
322                  */
323                 memset(r2t, 0, sizeof(*r2t));
324
325                 if (session->imm_data_en) {
326                         if (out_len >= session->first_burst)
327                                 task->imm_count = min(session->first_burst,
328                                                         conn->max_xmit_dlength);
329                         else
330                                 task->imm_count = min(out_len,
331                                                         conn->max_xmit_dlength);
332                         hton24(hdr->dlength, task->imm_count);
333                 } else
334                         zero_data(hdr->dlength);
335
336                 if (!session->initial_r2t_en) {
337                         r2t->data_length = min(session->first_burst, out_len) -
338                                                task->imm_count;
339                         r2t->data_offset = task->imm_count;
340                         r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
341                         r2t->exp_statsn = cpu_to_be32(conn->exp_statsn);
342                 }
343
344                 if (!task->unsol_r2t.data_length)
345                         /* No unsolicit Data-Out's */
346                         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
347         } else {
348                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
349                 zero_data(hdr->dlength);
350                 hdr->data_length = cpu_to_be32(scsi_in(sc)->length);
351
352                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
353                         hdr->flags |= ISCSI_FLAG_CMD_READ;
354         }
355
356         /* calculate size of additional header segments (AHSs) */
357         hdrlength = task->hdr_len - sizeof(*hdr);
358
359         WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
360         hdrlength /= ISCSI_PAD_LEN;
361
362         WARN_ON(hdrlength >= 256);
363         hdr->hlength = hdrlength & 0xFF;
364
365         if (session->tt->init_task && session->tt->init_task(task))
366                 return -EIO;
367
368         task->state = ISCSI_TASK_RUNNING;
369         list_move_tail(&task->running, &conn->run_list);
370
371         conn->scsicmd_pdus_cnt++;
372         ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x "
373                           "itt 0x%x len %d bidi_len %d cmdsn %d win %d]\n",
374                           scsi_bidi_cmnd(sc) ? "bidirectional" :
375                           sc->sc_data_direction == DMA_TO_DEVICE ?
376                           "write" : "read", conn->id, sc, sc->cmnd[0],
377                           task->itt, scsi_bufflen(sc),
378                           scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0,
379                           session->cmdsn,
380                           session->max_cmdsn - session->exp_cmdsn + 1);
381         return 0;
382 }
383
384 /**
385  * iscsi_complete_command - finish a task
386  * @task: iscsi cmd task
387  *
388  * Must be called with session lock.
389  * This function returns the scsi command to scsi-ml or cleans
390  * up mgmt tasks then returns the task to the pool.
391  */
392 static void iscsi_complete_command(struct iscsi_task *task)
393 {
394         struct iscsi_conn *conn = task->conn;
395         struct iscsi_session *session = conn->session;
396         struct scsi_cmnd *sc = task->sc;
397
398         session->tt->cleanup_task(task);
399         list_del_init(&task->running);
400         task->state = ISCSI_TASK_COMPLETED;
401         task->sc = NULL;
402
403         if (conn->task == task)
404                 conn->task = NULL;
405         /*
406          * login task is preallocated so do not free
407          */
408         if (conn->login_task == task)
409                 return;
410
411         __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*));
412
413         if (conn->ping_task == task)
414                 conn->ping_task = NULL;
415
416         if (sc) {
417                 task->sc = NULL;
418                 /* SCSI eh reuses commands to verify us */
419                 sc->SCp.ptr = NULL;
420                 /*
421                  * queue command may call this to free the task, but
422                  * not have setup the sc callback
423                  */
424                 if (sc->scsi_done)
425                         sc->scsi_done(sc);
426         }
427 }
428
429 void __iscsi_get_task(struct iscsi_task *task)
430 {
431         atomic_inc(&task->refcount);
432 }
433 EXPORT_SYMBOL_GPL(__iscsi_get_task);
434
435 static void __iscsi_put_task(struct iscsi_task *task)
436 {
437         if (atomic_dec_and_test(&task->refcount))
438                 iscsi_complete_command(task);
439 }
440
441 void iscsi_put_task(struct iscsi_task *task)
442 {
443         struct iscsi_session *session = task->conn->session;
444
445         spin_lock_bh(&session->lock);
446         __iscsi_put_task(task);
447         spin_unlock_bh(&session->lock);
448 }
449 EXPORT_SYMBOL_GPL(iscsi_put_task);
450
451 /*
452  * session lock must be held
453  */
454 static void fail_command(struct iscsi_conn *conn, struct iscsi_task *task,
455                          int err)
456 {
457         struct scsi_cmnd *sc;
458
459         sc = task->sc;
460         if (!sc)
461                 return;
462
463         if (task->state == ISCSI_TASK_PENDING)
464                 /*
465                  * cmd never made it to the xmit thread, so we should not count
466                  * the cmd in the sequencing
467                  */
468                 conn->session->queued_cmdsn--;
469
470         sc->result = err;
471         if (!scsi_bidi_cmnd(sc))
472                 scsi_set_resid(sc, scsi_bufflen(sc));
473         else {
474                 scsi_out(sc)->resid = scsi_out(sc)->length;
475                 scsi_in(sc)->resid = scsi_in(sc)->length;
476         }
477
478         if (conn->task == task)
479                 conn->task = NULL;
480         /* release ref from queuecommand */
481         __iscsi_put_task(task);
482 }
483
484 static int iscsi_prep_mgmt_task(struct iscsi_conn *conn,
485                                 struct iscsi_task *task)
486 {
487         struct iscsi_session *session = conn->session;
488         struct iscsi_hdr *hdr = task->hdr;
489         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
490
491         if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
492                 return -ENOTCONN;
493
494         if (hdr->opcode != (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) &&
495             hdr->opcode != (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
496                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
497         /*
498          * pre-format CmdSN for outgoing PDU.
499          */
500         nop->cmdsn = cpu_to_be32(session->cmdsn);
501         if (hdr->itt != RESERVED_ITT) {
502                 /*
503                  * TODO: We always use immediate, so we never hit this.
504                  * If we start to send tmfs or nops as non-immediate then
505                  * we should start checking the cmdsn numbers for mgmt tasks.
506                  */
507                 if (conn->c_stage == ISCSI_CONN_STARTED &&
508                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
509                         session->queued_cmdsn++;
510                         session->cmdsn++;
511                 }
512         }
513
514         if (session->tt->init_task && session->tt->init_task(task))
515                 return -EIO;
516
517         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
518                 session->state = ISCSI_STATE_LOGGING_OUT;
519
520         task->state = ISCSI_TASK_RUNNING;
521         list_move_tail(&task->running, &conn->mgmt_run_list);
522         ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x "
523                           "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK,
524                           hdr->itt, task->data_count);
525         return 0;
526 }
527
528 static struct iscsi_task *
529 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
530                       char *data, uint32_t data_size)
531 {
532         struct iscsi_session *session = conn->session;
533         struct iscsi_task *task;
534         itt_t itt;
535
536         if (session->state == ISCSI_STATE_TERMINATE)
537                 return NULL;
538
539         if (hdr->opcode == (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) ||
540             hdr->opcode == (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
541                 /*
542                  * Login and Text are sent serially, in
543                  * request-followed-by-response sequence.
544                  * Same task can be used. Same ITT must be used.
545                  * Note that login_task is preallocated at conn_create().
546                  */
547                 task = conn->login_task;
548         else {
549                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
550                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
551
552                 if (!__kfifo_get(session->cmdpool.queue,
553                                  (void*)&task, sizeof(void*)))
554                         return NULL;
555         }
556         /*
557          * released in complete pdu for task we expect a response for, and
558          * released by the lld when it has transmitted the task for
559          * pdus we do not expect a response for.
560          */
561         atomic_set(&task->refcount, 1);
562         task->conn = conn;
563         task->sc = NULL;
564
565         if (data_size) {
566                 memcpy(task->data, data, data_size);
567                 task->data_count = data_size;
568         } else
569                 task->data_count = 0;
570
571         if (conn->session->tt->alloc_pdu) {
572                 if (conn->session->tt->alloc_pdu(task, hdr->opcode)) {
573                         iscsi_conn_printk(KERN_ERR, conn, "Could not allocate "
574                                          "pdu for mgmt task.\n");
575                         goto requeue_task;
576                 }
577         }
578
579         itt = task->hdr->itt;
580         task->hdr_len = sizeof(struct iscsi_hdr);
581         memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr));
582
583         if (hdr->itt != RESERVED_ITT) {
584                 if (session->tt->parse_pdu_itt)
585                         task->hdr->itt = itt;
586                 else
587                         task->hdr->itt = build_itt(task->itt,
588                                                    task->conn->session->age);
589         }
590
591         INIT_LIST_HEAD(&task->running);
592         list_add_tail(&task->running, &conn->mgmtqueue);
593
594         if (session->tt->caps & CAP_DATA_PATH_OFFLOAD) {
595                 if (iscsi_prep_mgmt_task(conn, task))
596                         goto free_task;
597
598                 if (session->tt->xmit_task(task))
599                         goto free_task;
600
601         } else
602                 iscsi_conn_queue_work(conn);
603
604         return task;
605
606 free_task:
607         __iscsi_put_task(task);
608         return NULL;
609
610 requeue_task:
611         if (task != conn->login_task)
612                 __kfifo_put(session->cmdpool.queue, (void*)&task,
613                             sizeof(void*));
614         return NULL;
615 }
616
617 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
618                         char *data, uint32_t data_size)
619 {
620         struct iscsi_conn *conn = cls_conn->dd_data;
621         struct iscsi_session *session = conn->session;
622         int err = 0;
623
624         spin_lock_bh(&session->lock);
625         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
626                 err = -EPERM;
627         spin_unlock_bh(&session->lock);
628         return err;
629 }
630 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
631
632 /**
633  * iscsi_cmd_rsp - SCSI Command Response processing
634  * @conn: iscsi connection
635  * @hdr: iscsi header
636  * @task: scsi command task
637  * @data: cmd data buffer
638  * @datalen: len of buffer
639  *
640  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
641  * then completes the command and task.
642  **/
643 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
644                                struct iscsi_task *task, char *data,
645                                int datalen)
646 {
647         struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr;
648         struct iscsi_session *session = conn->session;
649         struct scsi_cmnd *sc = task->sc;
650
651         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
652         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
653
654         sc->result = (DID_OK << 16) | rhdr->cmd_status;
655
656         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
657                 sc->result = DID_ERROR << 16;
658                 goto out;
659         }
660
661         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
662                 uint16_t senselen;
663
664                 if (datalen < 2) {
665 invalid_datalen:
666                         iscsi_conn_printk(KERN_ERR,  conn,
667                                          "Got CHECK_CONDITION but invalid data "
668                                          "buffer size of %d\n", datalen);
669                         sc->result = DID_BAD_TARGET << 16;
670                         goto out;
671                 }
672
673                 senselen = get_unaligned_be16(data);
674                 if (datalen < senselen)
675                         goto invalid_datalen;
676
677                 memcpy(sc->sense_buffer, data + 2,
678                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
679                 ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n",
680                                   min_t(uint16_t, senselen,
681                                   SCSI_SENSE_BUFFERSIZE));
682         }
683
684         if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
685                            ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
686                 int res_count = be32_to_cpu(rhdr->bi_residual_count);
687
688                 if (scsi_bidi_cmnd(sc) && res_count > 0 &&
689                                 (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW ||
690                                  res_count <= scsi_in(sc)->length))
691                         scsi_in(sc)->resid = res_count;
692                 else
693                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
694         }
695
696         if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
697                            ISCSI_FLAG_CMD_OVERFLOW)) {
698                 int res_count = be32_to_cpu(rhdr->residual_count);
699
700                 if (res_count > 0 &&
701                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
702                      res_count <= scsi_bufflen(sc)))
703                         /* write side for bidi or uni-io set_resid */
704                         scsi_set_resid(sc, res_count);
705                 else
706                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
707         }
708 out:
709         ISCSI_DBG_SESSION(session, "done [sc %p res %d itt 0x%x]\n",
710                           sc, sc->result, task->itt);
711         conn->scsirsp_pdus_cnt++;
712
713         __iscsi_put_task(task);
714 }
715
716 /**
717  * iscsi_data_in_rsp - SCSI Data-In Response processing
718  * @conn: iscsi connection
719  * @hdr:  iscsi pdu
720  * @task: scsi command task
721  **/
722 static void
723 iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
724                   struct iscsi_task *task)
725 {
726         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr;
727         struct scsi_cmnd *sc = task->sc;
728
729         if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS))
730                 return;
731
732         iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr);
733         sc->result = (DID_OK << 16) | rhdr->cmd_status;
734         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
735         if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW |
736                            ISCSI_FLAG_DATA_OVERFLOW)) {
737                 int res_count = be32_to_cpu(rhdr->residual_count);
738
739                 if (res_count > 0 &&
740                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
741                      res_count <= scsi_in(sc)->length))
742                         scsi_in(sc)->resid = res_count;
743                 else
744                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
745         }
746
747         conn->scsirsp_pdus_cnt++;
748         __iscsi_put_task(task);
749 }
750
751 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
752 {
753         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
754
755         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
756         conn->tmfrsp_pdus_cnt++;
757
758         if (conn->tmf_state != TMF_QUEUED)
759                 return;
760
761         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
762                 conn->tmf_state = TMF_SUCCESS;
763         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
764                 conn->tmf_state = TMF_NOT_FOUND;
765         else
766                 conn->tmf_state = TMF_FAILED;
767         wake_up(&conn->ehwait);
768 }
769
770 static void iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
771 {
772         struct iscsi_nopout hdr;
773         struct iscsi_task *task;
774
775         if (!rhdr && conn->ping_task)
776                 return;
777
778         memset(&hdr, 0, sizeof(struct iscsi_nopout));
779         hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
780         hdr.flags = ISCSI_FLAG_CMD_FINAL;
781
782         if (rhdr) {
783                 memcpy(hdr.lun, rhdr->lun, 8);
784                 hdr.ttt = rhdr->ttt;
785                 hdr.itt = RESERVED_ITT;
786         } else
787                 hdr.ttt = RESERVED_ITT;
788
789         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
790         if (!task)
791                 iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
792         else if (!rhdr) {
793                 /* only track our nops */
794                 conn->ping_task = task;
795                 conn->last_ping = jiffies;
796         }
797 }
798
799 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
800                                char *data, int datalen)
801 {
802         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
803         struct iscsi_hdr rejected_pdu;
804
805         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
806
807         if (reject->reason == ISCSI_REASON_DATA_DIGEST_ERROR) {
808                 if (ntoh24(reject->dlength) > datalen)
809                         return ISCSI_ERR_PROTO;
810
811                 if (ntoh24(reject->dlength) >= sizeof(struct iscsi_hdr)) {
812                         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
813                         iscsi_conn_printk(KERN_ERR, conn,
814                                           "pdu (op 0x%x) rejected "
815                                           "due to DataDigest error.\n",
816                                           rejected_pdu.opcode);
817                 }
818         }
819         return 0;
820 }
821
822 /**
823  * iscsi_itt_to_task - look up task by itt
824  * @conn: iscsi connection
825  * @itt: itt
826  *
827  * This should be used for mgmt tasks like login and nops, or if
828  * the LDD's itt space does not include the session age.
829  *
830  * The session lock must be held.
831  */
832 struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
833 {
834         struct iscsi_session *session = conn->session;
835         int i;
836
837         if (itt == RESERVED_ITT)
838                 return NULL;
839
840         if (session->tt->parse_pdu_itt)
841                 session->tt->parse_pdu_itt(conn, itt, &i, NULL);
842         else
843                 i = get_itt(itt);
844         if (i >= session->cmds_max)
845                 return NULL;
846
847         return session->cmds[i];
848 }
849 EXPORT_SYMBOL_GPL(iscsi_itt_to_task);
850
851 /**
852  * __iscsi_complete_pdu - complete pdu
853  * @conn: iscsi conn
854  * @hdr: iscsi header
855  * @data: data buffer
856  * @datalen: len of data buffer
857  *
858  * Completes pdu processing by freeing any resources allocated at
859  * queuecommand or send generic. session lock must be held and verify
860  * itt must have been called.
861  */
862 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
863                          char *data, int datalen)
864 {
865         struct iscsi_session *session = conn->session;
866         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
867         struct iscsi_task *task;
868         uint32_t itt;
869
870         conn->last_recv = jiffies;
871         rc = iscsi_verify_itt(conn, hdr->itt);
872         if (rc)
873                 return rc;
874
875         if (hdr->itt != RESERVED_ITT)
876                 itt = get_itt(hdr->itt);
877         else
878                 itt = ~0U;
879
880         ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n",
881                           opcode, conn->id, itt, datalen);
882
883         if (itt == ~0U) {
884                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
885
886                 switch(opcode) {
887                 case ISCSI_OP_NOOP_IN:
888                         if (datalen) {
889                                 rc = ISCSI_ERR_PROTO;
890                                 break;
891                         }
892
893                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
894                                 break;
895
896                         iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
897                         break;
898                 case ISCSI_OP_REJECT:
899                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
900                         break;
901                 case ISCSI_OP_ASYNC_EVENT:
902                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
903                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
904                                 rc = ISCSI_ERR_CONN_FAILED;
905                         break;
906                 default:
907                         rc = ISCSI_ERR_BAD_OPCODE;
908                         break;
909                 }
910                 goto out;
911         }
912
913         switch(opcode) {
914         case ISCSI_OP_SCSI_CMD_RSP:
915         case ISCSI_OP_SCSI_DATA_IN:
916                 task = iscsi_itt_to_ctask(conn, hdr->itt);
917                 if (!task)
918                         return ISCSI_ERR_BAD_ITT;
919                 break;
920         case ISCSI_OP_R2T:
921                 /*
922                  * LLD handles R2Ts if they need to.
923                  */
924                 return 0;
925         case ISCSI_OP_LOGOUT_RSP:
926         case ISCSI_OP_LOGIN_RSP:
927         case ISCSI_OP_TEXT_RSP:
928         case ISCSI_OP_SCSI_TMFUNC_RSP:
929         case ISCSI_OP_NOOP_IN:
930                 task = iscsi_itt_to_task(conn, hdr->itt);
931                 if (!task)
932                         return ISCSI_ERR_BAD_ITT;
933                 break;
934         default:
935                 return ISCSI_ERR_BAD_OPCODE;
936         }
937
938         switch(opcode) {
939         case ISCSI_OP_SCSI_CMD_RSP:
940                 iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen);
941                 break;
942         case ISCSI_OP_SCSI_DATA_IN:
943                 iscsi_data_in_rsp(conn, hdr, task);
944                 break;
945         case ISCSI_OP_LOGOUT_RSP:
946                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
947                 if (datalen) {
948                         rc = ISCSI_ERR_PROTO;
949                         break;
950                 }
951                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
952                 goto recv_pdu;
953         case ISCSI_OP_LOGIN_RSP:
954         case ISCSI_OP_TEXT_RSP:
955                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
956                 /*
957                  * login related PDU's exp_statsn is handled in
958                  * userspace
959                  */
960                 goto recv_pdu;
961         case ISCSI_OP_SCSI_TMFUNC_RSP:
962                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
963                 if (datalen) {
964                         rc = ISCSI_ERR_PROTO;
965                         break;
966                 }
967
968                 iscsi_tmf_rsp(conn, hdr);
969                 __iscsi_put_task(task);
970                 break;
971         case ISCSI_OP_NOOP_IN:
972                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
973                 if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
974                         rc = ISCSI_ERR_PROTO;
975                         break;
976                 }
977                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
978
979                 if (conn->ping_task != task)
980                         /*
981                          * If this is not in response to one of our
982                          * nops then it must be from userspace.
983                          */
984                         goto recv_pdu;
985
986                 mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout);
987                 __iscsi_put_task(task);
988                 break;
989         default:
990                 rc = ISCSI_ERR_BAD_OPCODE;
991                 break;
992         }
993
994 out:
995         return rc;
996 recv_pdu:
997         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
998                 rc = ISCSI_ERR_CONN_FAILED;
999         __iscsi_put_task(task);
1000         return rc;
1001 }
1002 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
1003
1004 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1005                        char *data, int datalen)
1006 {
1007         int rc;
1008
1009         spin_lock(&conn->session->lock);
1010         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
1011         spin_unlock(&conn->session->lock);
1012         return rc;
1013 }
1014 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
1015
1016 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
1017 {
1018         struct iscsi_session *session = conn->session;
1019         int age = 0, i = 0;
1020
1021         if (itt == RESERVED_ITT)
1022                 return 0;
1023
1024         if (session->tt->parse_pdu_itt)
1025                 session->tt->parse_pdu_itt(conn, itt, &i, &age);
1026         else {
1027                 i = get_itt(itt);
1028                 age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK;
1029         }
1030
1031         if (age != session->age) {
1032                 iscsi_conn_printk(KERN_ERR, conn,
1033                                   "received itt %x expected session age (%x)\n",
1034                                   (__force u32)itt, session->age);
1035                 return ISCSI_ERR_BAD_ITT;
1036         }
1037
1038         if (i >= session->cmds_max) {
1039                 iscsi_conn_printk(KERN_ERR, conn,
1040                                   "received invalid itt index %u (max cmds "
1041                                    "%u.\n", i, session->cmds_max);
1042                 return ISCSI_ERR_BAD_ITT;
1043         }
1044         return 0;
1045 }
1046 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
1047
1048 /**
1049  * iscsi_itt_to_ctask - look up ctask by itt
1050  * @conn: iscsi connection
1051  * @itt: itt
1052  *
1053  * This should be used for cmd tasks.
1054  *
1055  * The session lock must be held.
1056  */
1057 struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
1058 {
1059         struct iscsi_task *task;
1060
1061         if (iscsi_verify_itt(conn, itt))
1062                 return NULL;
1063
1064         task = iscsi_itt_to_task(conn, itt);
1065         if (!task || !task->sc)
1066                 return NULL;
1067
1068         if (task->sc->SCp.phase != conn->session->age) {
1069                 iscsi_session_printk(KERN_ERR, conn->session,
1070                                   "task's session age %d, expected %d\n",
1071                                   task->sc->SCp.phase, conn->session->age);
1072                 return NULL;
1073         }
1074
1075         return task;
1076 }
1077 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
1078
1079 void iscsi_session_failure(struct iscsi_session *session,
1080                            enum iscsi_err err)
1081 {
1082         struct iscsi_conn *conn;
1083         struct device *dev;
1084         unsigned long flags;
1085
1086         spin_lock_irqsave(&session->lock, flags);
1087         conn = session->leadconn;
1088         if (session->state == ISCSI_STATE_TERMINATE || !conn) {
1089                 spin_unlock_irqrestore(&session->lock, flags);
1090                 return;
1091         }
1092
1093         dev = get_device(&conn->cls_conn->dev);
1094         spin_unlock_irqrestore(&session->lock, flags);
1095         if (!dev)
1096                 return;
1097         /*
1098          * if the host is being removed bypass the connection
1099          * recovery initialization because we are going to kill
1100          * the session.
1101          */
1102         if (err == ISCSI_ERR_INVALID_HOST)
1103                 iscsi_conn_error_event(conn->cls_conn, err);
1104         else
1105                 iscsi_conn_failure(conn, err);
1106         put_device(dev);
1107 }
1108 EXPORT_SYMBOL_GPL(iscsi_session_failure);
1109
1110 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
1111 {
1112         struct iscsi_session *session = conn->session;
1113         unsigned long flags;
1114
1115         spin_lock_irqsave(&session->lock, flags);
1116         if (session->state == ISCSI_STATE_FAILED) {
1117                 spin_unlock_irqrestore(&session->lock, flags);
1118                 return;
1119         }
1120
1121         if (conn->stop_stage == 0)
1122                 session->state = ISCSI_STATE_FAILED;
1123         spin_unlock_irqrestore(&session->lock, flags);
1124
1125         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1126         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1127         iscsi_conn_error_event(conn->cls_conn, err);
1128 }
1129 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
1130
1131 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
1132 {
1133         struct iscsi_session *session = conn->session;
1134
1135         /*
1136          * Check for iSCSI window and take care of CmdSN wrap-around
1137          */
1138         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
1139                 ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn "
1140                                   "%u MaxCmdSN %u CmdSN %u/%u\n",
1141                                   session->exp_cmdsn, session->max_cmdsn,
1142                                   session->cmdsn, session->queued_cmdsn);
1143                 return -ENOSPC;
1144         }
1145         return 0;
1146 }
1147
1148 static int iscsi_xmit_task(struct iscsi_conn *conn)
1149 {
1150         struct iscsi_task *task = conn->task;
1151         int rc;
1152
1153         __iscsi_get_task(task);
1154         spin_unlock_bh(&conn->session->lock);
1155         rc = conn->session->tt->xmit_task(task);
1156         spin_lock_bh(&conn->session->lock);
1157         __iscsi_put_task(task);
1158         if (!rc)
1159                 /* done with this task */
1160                 conn->task = NULL;
1161         return rc;
1162 }
1163
1164 /**
1165  * iscsi_requeue_task - requeue task to run from session workqueue
1166  * @task: task to requeue
1167  *
1168  * LLDs that need to run a task from the session workqueue should call
1169  * this. The session lock must be held. This should only be called
1170  * by software drivers.
1171  */
1172 void iscsi_requeue_task(struct iscsi_task *task)
1173 {
1174         struct iscsi_conn *conn = task->conn;
1175
1176         list_move_tail(&task->running, &conn->requeue);
1177         iscsi_conn_queue_work(conn);
1178 }
1179 EXPORT_SYMBOL_GPL(iscsi_requeue_task);
1180
1181 /**
1182  * iscsi_data_xmit - xmit any command into the scheduled connection
1183  * @conn: iscsi connection
1184  *
1185  * Notes:
1186  *      The function can return -EAGAIN in which case the caller must
1187  *      re-schedule it again later or recover. '0' return code means
1188  *      successful xmit.
1189  **/
1190 static int iscsi_data_xmit(struct iscsi_conn *conn)
1191 {
1192         int rc = 0;
1193
1194         spin_lock_bh(&conn->session->lock);
1195         if (unlikely(conn->suspend_tx)) {
1196                 ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n");
1197                 spin_unlock_bh(&conn->session->lock);
1198                 return -ENODATA;
1199         }
1200
1201         if (conn->task) {
1202                 rc = iscsi_xmit_task(conn);
1203                 if (rc)
1204                         goto again;
1205         }
1206
1207         /*
1208          * process mgmt pdus like nops before commands since we should
1209          * only have one nop-out as a ping from us and targets should not
1210          * overflow us with nop-ins
1211          */
1212 check_mgmt:
1213         while (!list_empty(&conn->mgmtqueue)) {
1214                 conn->task = list_entry(conn->mgmtqueue.next,
1215                                          struct iscsi_task, running);
1216                 if (iscsi_prep_mgmt_task(conn, conn->task)) {
1217                         __iscsi_put_task(conn->task);
1218                         conn->task = NULL;
1219                         continue;
1220                 }
1221                 rc = iscsi_xmit_task(conn);
1222                 if (rc)
1223                         goto again;
1224         }
1225
1226         /* process pending command queue */
1227         while (!list_empty(&conn->xmitqueue)) {
1228                 if (conn->tmf_state == TMF_QUEUED)
1229                         break;
1230
1231                 conn->task = list_entry(conn->xmitqueue.next,
1232                                          struct iscsi_task, running);
1233                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1234                         fail_command(conn, conn->task, DID_IMM_RETRY << 16);
1235                         continue;
1236                 }
1237                 rc = iscsi_prep_scsi_cmd_pdu(conn->task);
1238                 if (rc) {
1239                         if (rc == -ENOMEM) {
1240                                 conn->task = NULL;
1241                                 goto again;
1242                         } else
1243                                 fail_command(conn, conn->task, DID_ABORT << 16);
1244                         continue;
1245                 }
1246                 rc = iscsi_xmit_task(conn);
1247                 if (rc)
1248                         goto again;
1249                 /*
1250                  * we could continuously get new task requests so
1251                  * we need to check the mgmt queue for nops that need to
1252                  * be sent to aviod starvation
1253                  */
1254                 if (!list_empty(&conn->mgmtqueue))
1255                         goto check_mgmt;
1256         }
1257
1258         while (!list_empty(&conn->requeue)) {
1259                 if (conn->session->fast_abort && conn->tmf_state != TMF_INITIAL)
1260                         break;
1261
1262                 /*
1263                  * we always do fastlogout - conn stop code will clean up.
1264                  */
1265                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1266                         break;
1267
1268                 conn->task = list_entry(conn->requeue.next,
1269                                          struct iscsi_task, running);
1270                 conn->task->state = ISCSI_TASK_RUNNING;
1271                 list_move_tail(conn->requeue.next, &conn->run_list);
1272                 rc = iscsi_xmit_task(conn);
1273                 if (rc)
1274                         goto again;
1275                 if (!list_empty(&conn->mgmtqueue))
1276                         goto check_mgmt;
1277         }
1278         spin_unlock_bh(&conn->session->lock);
1279         return -ENODATA;
1280
1281 again:
1282         if (unlikely(conn->suspend_tx))
1283                 rc = -ENODATA;
1284         spin_unlock_bh(&conn->session->lock);
1285         return rc;
1286 }
1287
1288 static void iscsi_xmitworker(struct work_struct *work)
1289 {
1290         struct iscsi_conn *conn =
1291                 container_of(work, struct iscsi_conn, xmitwork);
1292         int rc;
1293         /*
1294          * serialize Xmit worker on a per-connection basis.
1295          */
1296         do {
1297                 rc = iscsi_data_xmit(conn);
1298         } while (rc >= 0 || rc == -EAGAIN);
1299 }
1300
1301 static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn,
1302                                                   struct scsi_cmnd *sc)
1303 {
1304         struct iscsi_task *task;
1305
1306         if (!__kfifo_get(conn->session->cmdpool.queue,
1307                          (void *) &task, sizeof(void *)))
1308                 return NULL;
1309
1310         sc->SCp.phase = conn->session->age;
1311         sc->SCp.ptr = (char *) task;
1312
1313         atomic_set(&task->refcount, 1);
1314         task->state = ISCSI_TASK_PENDING;
1315         task->conn = conn;
1316         task->sc = sc;
1317         INIT_LIST_HEAD(&task->running);
1318         return task;
1319 }
1320
1321 enum {
1322         FAILURE_BAD_HOST = 1,
1323         FAILURE_SESSION_FAILED,
1324         FAILURE_SESSION_FREED,
1325         FAILURE_WINDOW_CLOSED,
1326         FAILURE_OOM,
1327         FAILURE_SESSION_TERMINATE,
1328         FAILURE_SESSION_IN_RECOVERY,
1329         FAILURE_SESSION_RECOVERY_TIMEOUT,
1330         FAILURE_SESSION_LOGGING_OUT,
1331         FAILURE_SESSION_NOT_READY,
1332 };
1333
1334 int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *))
1335 {
1336         struct iscsi_cls_session *cls_session;
1337         struct Scsi_Host *host;
1338         int reason = 0;
1339         struct iscsi_session *session;
1340         struct iscsi_conn *conn;
1341         struct iscsi_task *task = NULL;
1342
1343         sc->scsi_done = done;
1344         sc->result = 0;
1345         sc->SCp.ptr = NULL;
1346
1347         host = sc->device->host;
1348         spin_unlock(host->host_lock);
1349
1350         cls_session = starget_to_session(scsi_target(sc->device));
1351         session = cls_session->dd_data;
1352         spin_lock(&session->lock);
1353
1354         reason = iscsi_session_chkready(cls_session);
1355         if (reason) {
1356                 sc->result = reason;
1357                 goto fault;
1358         }
1359
1360         /*
1361          * ISCSI_STATE_FAILED is a temp. state. The recovery
1362          * code will decide what is best to do with command queued
1363          * during this time
1364          */
1365         if (session->state != ISCSI_STATE_LOGGED_IN &&
1366             session->state != ISCSI_STATE_FAILED) {
1367                 /*
1368                  * to handle the race between when we set the recovery state
1369                  * and block the session we requeue here (commands could
1370                  * be entering our queuecommand while a block is starting
1371                  * up because the block code is not locked)
1372                  */
1373                 switch (session->state) {
1374                 case ISCSI_STATE_IN_RECOVERY:
1375                         reason = FAILURE_SESSION_IN_RECOVERY;
1376                         goto reject;
1377                 case ISCSI_STATE_LOGGING_OUT:
1378                         reason = FAILURE_SESSION_LOGGING_OUT;
1379                         goto reject;
1380                 case ISCSI_STATE_RECOVERY_FAILED:
1381                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1382                         sc->result = DID_TRANSPORT_FAILFAST << 16;
1383                         break;
1384                 case ISCSI_STATE_TERMINATE:
1385                         reason = FAILURE_SESSION_TERMINATE;
1386                         sc->result = DID_NO_CONNECT << 16;
1387                         break;
1388                 default:
1389                         reason = FAILURE_SESSION_FREED;
1390                         sc->result = DID_NO_CONNECT << 16;
1391                 }
1392                 goto fault;
1393         }
1394
1395         conn = session->leadconn;
1396         if (!conn) {
1397                 reason = FAILURE_SESSION_FREED;
1398                 sc->result = DID_NO_CONNECT << 16;
1399                 goto fault;
1400         }
1401
1402         if (iscsi_check_cmdsn_window_closed(conn)) {
1403                 reason = FAILURE_WINDOW_CLOSED;
1404                 goto reject;
1405         }
1406
1407         task = iscsi_alloc_task(conn, sc);
1408         if (!task) {
1409                 reason = FAILURE_OOM;
1410                 goto reject;
1411         }
1412         list_add_tail(&task->running, &conn->xmitqueue);
1413
1414         if (session->tt->caps & CAP_DATA_PATH_OFFLOAD) {
1415                 reason = iscsi_prep_scsi_cmd_pdu(task);
1416                 if (reason) {
1417                         if (reason == -ENOMEM) {
1418                                 reason = FAILURE_OOM;
1419                                 goto prepd_reject;
1420                         } else {
1421                                 sc->result = DID_ABORT << 16;
1422                                 goto prepd_fault;
1423                         }
1424                 }
1425                 if (session->tt->xmit_task(task)) {
1426                         reason = FAILURE_SESSION_NOT_READY;
1427                         goto prepd_reject;
1428                 }
1429         } else
1430                 iscsi_conn_queue_work(conn);
1431
1432         session->queued_cmdsn++;
1433         spin_unlock(&session->lock);
1434         spin_lock(host->host_lock);
1435         return 0;
1436
1437 prepd_reject:
1438         sc->scsi_done = NULL;
1439         iscsi_complete_command(task);
1440 reject:
1441         spin_unlock(&session->lock);
1442         ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n",
1443                           sc->cmnd[0], reason);
1444         spin_lock(host->host_lock);
1445         return SCSI_MLQUEUE_TARGET_BUSY;
1446
1447 prepd_fault:
1448         sc->scsi_done = NULL;
1449         iscsi_complete_command(task);
1450 fault:
1451         spin_unlock(&session->lock);
1452         ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n",
1453                           sc->cmnd[0], reason);
1454         if (!scsi_bidi_cmnd(sc))
1455                 scsi_set_resid(sc, scsi_bufflen(sc));
1456         else {
1457                 scsi_out(sc)->resid = scsi_out(sc)->length;
1458                 scsi_in(sc)->resid = scsi_in(sc)->length;
1459         }
1460         done(sc);
1461         spin_lock(host->host_lock);
1462         return 0;
1463 }
1464 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1465
1466 int iscsi_change_queue_depth(struct scsi_device *sdev, int depth)
1467 {
1468         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
1469         return sdev->queue_depth;
1470 }
1471 EXPORT_SYMBOL_GPL(iscsi_change_queue_depth);
1472
1473 int iscsi_target_alloc(struct scsi_target *starget)
1474 {
1475         struct iscsi_cls_session *cls_session = starget_to_session(starget);
1476         struct iscsi_session *session = cls_session->dd_data;
1477
1478         starget->can_queue = session->scsi_cmds_max;
1479         return 0;
1480 }
1481 EXPORT_SYMBOL_GPL(iscsi_target_alloc);
1482
1483 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
1484 {
1485         struct iscsi_session *session = cls_session->dd_data;
1486
1487         spin_lock_bh(&session->lock);
1488         if (session->state != ISCSI_STATE_LOGGED_IN) {
1489                 session->state = ISCSI_STATE_RECOVERY_FAILED;
1490                 if (session->leadconn)
1491                         wake_up(&session->leadconn->ehwait);
1492         }
1493         spin_unlock_bh(&session->lock);
1494 }
1495 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
1496
1497 int iscsi_eh_target_reset(struct scsi_cmnd *sc)
1498 {
1499         struct iscsi_cls_session *cls_session;
1500         struct iscsi_session *session;
1501         struct iscsi_conn *conn;
1502
1503         cls_session = starget_to_session(scsi_target(sc->device));
1504         session = cls_session->dd_data;
1505         conn = session->leadconn;
1506
1507         mutex_lock(&session->eh_mutex);
1508         spin_lock_bh(&session->lock);
1509         if (session->state == ISCSI_STATE_TERMINATE) {
1510 failed:
1511                 iscsi_session_printk(KERN_INFO, session,
1512                                      "failing target reset: Could not log "
1513                                      "back into target [age %d]\n",
1514                                      session->age);
1515                 spin_unlock_bh(&session->lock);
1516                 mutex_unlock(&session->eh_mutex);
1517                 return FAILED;
1518         }
1519
1520         spin_unlock_bh(&session->lock);
1521         mutex_unlock(&session->eh_mutex);
1522         /*
1523          * we drop the lock here but the leadconn cannot be destoyed while
1524          * we are in the scsi eh
1525          */
1526         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1527
1528         ISCSI_DBG_SESSION(session, "wait for relogin\n");
1529         wait_event_interruptible(conn->ehwait,
1530                                  session->state == ISCSI_STATE_TERMINATE ||
1531                                  session->state == ISCSI_STATE_LOGGED_IN ||
1532                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
1533         if (signal_pending(current))
1534                 flush_signals(current);
1535
1536         mutex_lock(&session->eh_mutex);
1537         spin_lock_bh(&session->lock);
1538         if (session->state == ISCSI_STATE_LOGGED_IN)
1539                 iscsi_session_printk(KERN_INFO, session,
1540                                      "target reset succeeded\n");
1541         else
1542                 goto failed;
1543         spin_unlock_bh(&session->lock);
1544         mutex_unlock(&session->eh_mutex);
1545         return SUCCESS;
1546 }
1547 EXPORT_SYMBOL_GPL(iscsi_eh_target_reset);
1548
1549 static void iscsi_tmf_timedout(unsigned long data)
1550 {
1551         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1552         struct iscsi_session *session = conn->session;
1553
1554         spin_lock(&session->lock);
1555         if (conn->tmf_state == TMF_QUEUED) {
1556                 conn->tmf_state = TMF_TIMEDOUT;
1557                 ISCSI_DBG_SESSION(session, "tmf timedout\n");
1558                 /* unblock eh_abort() */
1559                 wake_up(&conn->ehwait);
1560         }
1561         spin_unlock(&session->lock);
1562 }
1563
1564 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1565                                    struct iscsi_tm *hdr, int age,
1566                                    int timeout)
1567 {
1568         struct iscsi_session *session = conn->session;
1569         struct iscsi_task *task;
1570
1571         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1572                                       NULL, 0);
1573         if (!task) {
1574                 spin_unlock_bh(&session->lock);
1575                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1576                 spin_lock_bh(&session->lock);
1577                 ISCSI_DBG_SESSION(session, "tmf exec failure\n");
1578                 return -EPERM;
1579         }
1580         conn->tmfcmd_pdus_cnt++;
1581         conn->tmf_timer.expires = timeout * HZ + jiffies;
1582         conn->tmf_timer.function = iscsi_tmf_timedout;
1583         conn->tmf_timer.data = (unsigned long)conn;
1584         add_timer(&conn->tmf_timer);
1585         ISCSI_DBG_SESSION(session, "tmf set timeout\n");
1586
1587         spin_unlock_bh(&session->lock);
1588         mutex_unlock(&session->eh_mutex);
1589
1590         /*
1591          * block eh thread until:
1592          *
1593          * 1) tmf response
1594          * 2) tmf timeout
1595          * 3) session is terminated or restarted or userspace has
1596          * given up on recovery
1597          */
1598         wait_event_interruptible(conn->ehwait, age != session->age ||
1599                                  session->state != ISCSI_STATE_LOGGED_IN ||
1600                                  conn->tmf_state != TMF_QUEUED);
1601         if (signal_pending(current))
1602                 flush_signals(current);
1603         del_timer_sync(&conn->tmf_timer);
1604
1605         mutex_lock(&session->eh_mutex);
1606         spin_lock_bh(&session->lock);
1607         /* if the session drops it will clean up the task */
1608         if (age != session->age ||
1609             session->state != ISCSI_STATE_LOGGED_IN)
1610                 return -ENOTCONN;
1611         return 0;
1612 }
1613
1614 /*
1615  * Fail commands. session lock held and recv side suspended and xmit
1616  * thread flushed
1617  */
1618 static void fail_all_commands(struct iscsi_conn *conn, unsigned lun,
1619                               int error)
1620 {
1621         struct iscsi_task *task, *tmp;
1622
1623         if (conn->task) {
1624                 if (lun == -1 ||
1625                     (conn->task->sc && conn->task->sc->device->lun == lun))
1626                         conn->task = NULL;
1627         }
1628
1629         /* flush pending */
1630         list_for_each_entry_safe(task, tmp, &conn->xmitqueue, running) {
1631                 if (lun == task->sc->device->lun || lun == -1) {
1632                         ISCSI_DBG_SESSION(conn->session,
1633                                           "failing pending sc %p itt 0x%x\n",
1634                                           task->sc, task->itt);
1635                         fail_command(conn, task, error << 16);
1636                 }
1637         }
1638
1639         list_for_each_entry_safe(task, tmp, &conn->requeue, running) {
1640                 if (lun == task->sc->device->lun || lun == -1) {
1641                         ISCSI_DBG_SESSION(conn->session,
1642                                           "failing requeued sc %p itt 0x%x\n",
1643                                           task->sc, task->itt);
1644                         fail_command(conn, task, error << 16);
1645                 }
1646         }
1647
1648         /* fail all other running */
1649         list_for_each_entry_safe(task, tmp, &conn->run_list, running) {
1650                 if (lun == task->sc->device->lun || lun == -1) {
1651                         ISCSI_DBG_SESSION(conn->session,
1652                                          "failing in progress sc %p itt 0x%x\n",
1653                                          task->sc, task->itt);
1654                         fail_command(conn, task, error << 16);
1655                 }
1656         }
1657 }
1658
1659 void iscsi_suspend_tx(struct iscsi_conn *conn)
1660 {
1661         struct Scsi_Host *shost = conn->session->host;
1662         struct iscsi_host *ihost = shost_priv(shost);
1663
1664         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1665         if (!(conn->session->tt->caps & CAP_DATA_PATH_OFFLOAD))
1666                 flush_workqueue(ihost->workq);
1667 }
1668 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1669
1670 static void iscsi_start_tx(struct iscsi_conn *conn)
1671 {
1672         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1673         if (!(conn->session->tt->caps & CAP_DATA_PATH_OFFLOAD))
1674                 iscsi_conn_queue_work(conn);
1675 }
1676
1677 static enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *scmd)
1678 {
1679         struct iscsi_cls_session *cls_session;
1680         struct iscsi_session *session;
1681         struct iscsi_conn *conn;
1682         enum blk_eh_timer_return rc = BLK_EH_NOT_HANDLED;
1683
1684         cls_session = starget_to_session(scsi_target(scmd->device));
1685         session = cls_session->dd_data;
1686
1687         ISCSI_DBG_SESSION(session, "scsi cmd %p timedout\n", scmd);
1688
1689         spin_lock(&session->lock);
1690         if (session->state != ISCSI_STATE_LOGGED_IN) {
1691                 /*
1692                  * We are probably in the middle of iscsi recovery so let
1693                  * that complete and handle the error.
1694                  */
1695                 rc = BLK_EH_RESET_TIMER;
1696                 goto done;
1697         }
1698
1699         conn = session->leadconn;
1700         if (!conn) {
1701                 /* In the middle of shuting down */
1702                 rc = BLK_EH_RESET_TIMER;
1703                 goto done;
1704         }
1705
1706         if (!conn->recv_timeout && !conn->ping_timeout)
1707                 goto done;
1708         /*
1709          * if the ping timedout then we are in the middle of cleaning up
1710          * and can let the iscsi eh handle it
1711          */
1712         if (time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1713                             (conn->ping_timeout * HZ), jiffies))
1714                 rc = BLK_EH_RESET_TIMER;
1715         /*
1716          * if we are about to check the transport then give the command
1717          * more time
1718          */
1719         if (time_before_eq(conn->last_recv + (conn->recv_timeout * HZ),
1720                            jiffies))
1721                 rc = BLK_EH_RESET_TIMER;
1722         /* if in the middle of checking the transport then give us more time */
1723         if (conn->ping_task)
1724                 rc = BLK_EH_RESET_TIMER;
1725 done:
1726         spin_unlock(&session->lock);
1727         ISCSI_DBG_SESSION(session, "return %s\n", rc == BLK_EH_RESET_TIMER ?
1728                           "timer reset" : "nh");
1729         return rc;
1730 }
1731
1732 static void iscsi_check_transport_timeouts(unsigned long data)
1733 {
1734         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1735         struct iscsi_session *session = conn->session;
1736         unsigned long recv_timeout, next_timeout = 0, last_recv;
1737
1738         spin_lock(&session->lock);
1739         if (session->state != ISCSI_STATE_LOGGED_IN)
1740                 goto done;
1741
1742         recv_timeout = conn->recv_timeout;
1743         if (!recv_timeout)
1744                 goto done;
1745
1746         recv_timeout *= HZ;
1747         last_recv = conn->last_recv;
1748         if (conn->ping_task &&
1749             time_before_eq(conn->last_ping + (conn->ping_timeout * HZ),
1750                            jiffies)) {
1751                 iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
1752                                   "expired, last rx %lu, last ping %lu, "
1753                                   "now %lu\n", conn->ping_timeout, last_recv,
1754                                   conn->last_ping, jiffies);
1755                 spin_unlock(&session->lock);
1756                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1757                 return;
1758         }
1759
1760         if (time_before_eq(last_recv + recv_timeout, jiffies)) {
1761                 /* send a ping to try to provoke some traffic */
1762                 ISCSI_DBG_CONN(conn, "Sending nopout as ping\n");
1763                 iscsi_send_nopout(conn, NULL);
1764                 next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
1765         } else
1766                 next_timeout = last_recv + recv_timeout;
1767
1768         ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout);
1769         mod_timer(&conn->transport_timer, next_timeout);
1770 done:
1771         spin_unlock(&session->lock);
1772 }
1773
1774 static void iscsi_prep_abort_task_pdu(struct iscsi_task *task,
1775                                       struct iscsi_tm *hdr)
1776 {
1777         memset(hdr, 0, sizeof(*hdr));
1778         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1779         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
1780         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1781         memcpy(hdr->lun, task->lun, sizeof(hdr->lun));
1782         hdr->rtt = task->hdr_itt;
1783         hdr->refcmdsn = task->cmdsn;
1784 }
1785
1786 int iscsi_eh_abort(struct scsi_cmnd *sc)
1787 {
1788         struct iscsi_cls_session *cls_session;
1789         struct iscsi_session *session;
1790         struct iscsi_conn *conn;
1791         struct iscsi_task *task;
1792         struct iscsi_tm *hdr;
1793         int rc, age;
1794
1795         cls_session = starget_to_session(scsi_target(sc->device));
1796         session = cls_session->dd_data;
1797
1798         mutex_lock(&session->eh_mutex);
1799         spin_lock_bh(&session->lock);
1800         /*
1801          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
1802          * got the command.
1803          */
1804         if (!sc->SCp.ptr) {
1805                 ISCSI_DBG_SESSION(session, "sc never reached iscsi layer or "
1806                                   "it completed.\n");
1807                 spin_unlock_bh(&session->lock);
1808                 mutex_unlock(&session->eh_mutex);
1809                 return SUCCESS;
1810         }
1811
1812         /*
1813          * If we are not logged in or we have started a new session
1814          * then let the host reset code handle this
1815          */
1816         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
1817             sc->SCp.phase != session->age) {
1818                 spin_unlock_bh(&session->lock);
1819                 mutex_unlock(&session->eh_mutex);
1820                 return FAILED;
1821         }
1822
1823         conn = session->leadconn;
1824         conn->eh_abort_cnt++;
1825         age = session->age;
1826
1827         task = (struct iscsi_task *)sc->SCp.ptr;
1828         ISCSI_DBG_SESSION(session, "aborting [sc %p itt 0x%x]\n",
1829                           sc, task->itt);
1830
1831         /* task completed before time out */
1832         if (!task->sc) {
1833                 ISCSI_DBG_SESSION(session, "sc completed while abort in "
1834                                   "progress\n");
1835                 goto success;
1836         }
1837
1838         if (task->state == ISCSI_TASK_PENDING) {
1839                 fail_command(conn, task, DID_ABORT << 16);
1840                 goto success;
1841         }
1842
1843         /* only have one tmf outstanding at a time */
1844         if (conn->tmf_state != TMF_INITIAL)
1845                 goto failed;
1846         conn->tmf_state = TMF_QUEUED;
1847
1848         hdr = &conn->tmhdr;
1849         iscsi_prep_abort_task_pdu(task, hdr);
1850
1851         if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout)) {
1852                 rc = FAILED;
1853                 goto failed;
1854         }
1855
1856         switch (conn->tmf_state) {
1857         case TMF_SUCCESS:
1858                 spin_unlock_bh(&session->lock);
1859                 /*
1860                  * stop tx side incase the target had sent a abort rsp but
1861                  * the initiator was still writing out data.
1862                  */
1863                 iscsi_suspend_tx(conn);
1864                 /*
1865                  * we do not stop the recv side because targets have been
1866                  * good and have never sent us a successful tmf response
1867                  * then sent more data for the cmd.
1868                  */
1869                 spin_lock(&session->lock);
1870                 fail_command(conn, task, DID_ABORT << 16);
1871                 conn->tmf_state = TMF_INITIAL;
1872                 spin_unlock(&session->lock);
1873                 iscsi_start_tx(conn);
1874                 goto success_unlocked;
1875         case TMF_TIMEDOUT:
1876                 spin_unlock_bh(&session->lock);
1877                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1878                 goto failed_unlocked;
1879         case TMF_NOT_FOUND:
1880                 if (!sc->SCp.ptr) {
1881                         conn->tmf_state = TMF_INITIAL;
1882                         /* task completed before tmf abort response */
1883                         ISCSI_DBG_SESSION(session, "sc completed while abort "
1884                                           "in progress\n");
1885                         goto success;
1886                 }
1887                 /* fall through */
1888         default:
1889                 conn->tmf_state = TMF_INITIAL;
1890                 goto failed;
1891         }
1892
1893 success:
1894         spin_unlock_bh(&session->lock);
1895 success_unlocked:
1896         ISCSI_DBG_SESSION(session, "abort success [sc %p itt 0x%x]\n",
1897                           sc, task->itt);
1898         mutex_unlock(&session->eh_mutex);
1899         return SUCCESS;
1900
1901 failed:
1902         spin_unlock_bh(&session->lock);
1903 failed_unlocked:
1904         ISCSI_DBG_SESSION(session, "abort failed [sc %p itt 0x%x]\n", sc,
1905                           task ? task->itt : 0);
1906         mutex_unlock(&session->eh_mutex);
1907         return FAILED;
1908 }
1909 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
1910
1911 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
1912 {
1913         memset(hdr, 0, sizeof(*hdr));
1914         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1915         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
1916         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1917         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
1918         hdr->rtt = RESERVED_ITT;
1919 }
1920
1921 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
1922 {
1923         struct iscsi_cls_session *cls_session;
1924         struct iscsi_session *session;
1925         struct iscsi_conn *conn;
1926         struct iscsi_tm *hdr;
1927         int rc = FAILED;
1928
1929         cls_session = starget_to_session(scsi_target(sc->device));
1930         session = cls_session->dd_data;
1931
1932         ISCSI_DBG_SESSION(session, "LU Reset [sc %p lun %u]\n",
1933                           sc, sc->device->lun);
1934
1935         mutex_lock(&session->eh_mutex);
1936         spin_lock_bh(&session->lock);
1937         /*
1938          * Just check if we are not logged in. We cannot check for
1939          * the phase because the reset could come from a ioctl.
1940          */
1941         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
1942                 goto unlock;
1943         conn = session->leadconn;
1944
1945         /* only have one tmf outstanding at a time */
1946         if (conn->tmf_state != TMF_INITIAL)
1947                 goto unlock;
1948         conn->tmf_state = TMF_QUEUED;
1949
1950         hdr = &conn->tmhdr;
1951         iscsi_prep_lun_reset_pdu(sc, hdr);
1952
1953         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
1954                                     session->lu_reset_timeout)) {
1955                 rc = FAILED;
1956                 goto unlock;
1957         }
1958
1959         switch (conn->tmf_state) {
1960         case TMF_SUCCESS:
1961                 break;
1962         case TMF_TIMEDOUT:
1963                 spin_unlock_bh(&session->lock);
1964                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1965                 goto done;
1966         default:
1967                 conn->tmf_state = TMF_INITIAL;
1968                 goto unlock;
1969         }
1970
1971         rc = SUCCESS;
1972         spin_unlock_bh(&session->lock);
1973
1974         iscsi_suspend_tx(conn);
1975
1976         spin_lock_bh(&session->lock);
1977         fail_all_commands(conn, sc->device->lun, DID_ERROR);
1978         conn->tmf_state = TMF_INITIAL;
1979         spin_unlock_bh(&session->lock);
1980
1981         iscsi_start_tx(conn);
1982         goto done;
1983
1984 unlock:
1985         spin_unlock_bh(&session->lock);
1986 done:
1987         ISCSI_DBG_SESSION(session, "dev reset result = %s\n",
1988                          rc == SUCCESS ? "SUCCESS" : "FAILED");
1989         mutex_unlock(&session->eh_mutex);
1990         return rc;
1991 }
1992 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
1993
1994 /*
1995  * Pre-allocate a pool of @max items of @item_size. By default, the pool
1996  * should be accessed via kfifo_{get,put} on q->queue.
1997  * Optionally, the caller can obtain the array of object pointers
1998  * by passing in a non-NULL @items pointer
1999  */
2000 int
2001 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
2002 {
2003         int i, num_arrays = 1;
2004
2005         memset(q, 0, sizeof(*q));
2006
2007         q->max = max;
2008
2009         /* If the user passed an items pointer, he wants a copy of
2010          * the array. */
2011         if (items)
2012                 num_arrays++;
2013         q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL);
2014         if (q->pool == NULL)
2015                 return -ENOMEM;
2016
2017         q->queue = kfifo_init((void*)q->pool, max * sizeof(void*),
2018                               GFP_KERNEL, NULL);
2019         if (IS_ERR(q->queue)) {
2020                 q->queue = NULL;
2021                 goto enomem;
2022         }
2023
2024         for (i = 0; i < max; i++) {
2025                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
2026                 if (q->pool[i] == NULL) {
2027                         q->max = i;
2028                         goto enomem;
2029                 }
2030                 __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*));
2031         }
2032
2033         if (items) {
2034                 *items = q->pool + max;
2035                 memcpy(*items, q->pool, max * sizeof(void *));
2036         }
2037
2038         return 0;
2039
2040 enomem:
2041         iscsi_pool_free(q);
2042         return -ENOMEM;
2043 }
2044 EXPORT_SYMBOL_GPL(iscsi_pool_init);
2045
2046 void iscsi_pool_free(struct iscsi_pool *q)
2047 {
2048         int i;
2049
2050         for (i = 0; i < q->max; i++)
2051                 kfree(q->pool[i]);
2052         kfree(q->pool);
2053         kfree(q->queue);
2054 }
2055 EXPORT_SYMBOL_GPL(iscsi_pool_free);
2056
2057 /**
2058  * iscsi_host_add - add host to system
2059  * @shost: scsi host
2060  * @pdev: parent device
2061  *
2062  * This should be called by partial offload and software iscsi drivers
2063  * to add a host to the system.
2064  */
2065 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
2066 {
2067         if (!shost->can_queue)
2068                 shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX;
2069
2070         if (!shost->cmd_per_lun)
2071                 shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN;
2072
2073         if (!shost->transportt->eh_timed_out)
2074                 shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out;
2075         return scsi_add_host(shost, pdev);
2076 }
2077 EXPORT_SYMBOL_GPL(iscsi_host_add);
2078
2079 /**
2080  * iscsi_host_alloc - allocate a host and driver data
2081  * @sht: scsi host template
2082  * @dd_data_size: driver host data size
2083  * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue
2084  *
2085  * This should be called by partial offload and software iscsi drivers.
2086  * To access the driver specific memory use the iscsi_host_priv() macro.
2087  */
2088 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
2089                                    int dd_data_size, bool xmit_can_sleep)
2090 {
2091         struct Scsi_Host *shost;
2092         struct iscsi_host *ihost;
2093
2094         shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
2095         if (!shost)
2096                 return NULL;
2097         ihost = shost_priv(shost);
2098
2099         if (xmit_can_sleep) {
2100                 snprintf(ihost->workq_name, sizeof(ihost->workq_name),
2101                         "iscsi_q_%d", shost->host_no);
2102                 ihost->workq = create_singlethread_workqueue(ihost->workq_name);
2103                 if (!ihost->workq)
2104                         goto free_host;
2105         }
2106
2107         spin_lock_init(&ihost->lock);
2108         ihost->state = ISCSI_HOST_SETUP;
2109         ihost->num_sessions = 0;
2110         init_waitqueue_head(&ihost->session_removal_wq);
2111         return shost;
2112
2113 free_host:
2114         scsi_host_put(shost);
2115         return NULL;
2116 }
2117 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
2118
2119 static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session)
2120 {
2121         iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST);
2122 }
2123
2124 /**
2125  * iscsi_host_remove - remove host and sessions
2126  * @shost: scsi host
2127  *
2128  * If there are any sessions left, this will initiate the removal and wait
2129  * for the completion.
2130  */
2131 void iscsi_host_remove(struct Scsi_Host *shost)
2132 {
2133         struct iscsi_host *ihost = shost_priv(shost);
2134         unsigned long flags;
2135
2136         spin_lock_irqsave(&ihost->lock, flags);
2137         ihost->state = ISCSI_HOST_REMOVED;
2138         spin_unlock_irqrestore(&ihost->lock, flags);
2139
2140         iscsi_host_for_each_session(shost, iscsi_notify_host_removed);
2141         wait_event_interruptible(ihost->session_removal_wq,
2142                                  ihost->num_sessions == 0);
2143         if (signal_pending(current))
2144                 flush_signals(current);
2145
2146         scsi_remove_host(shost);
2147         if (ihost->workq)
2148                 destroy_workqueue(ihost->workq);
2149 }
2150 EXPORT_SYMBOL_GPL(iscsi_host_remove);
2151
2152 void iscsi_host_free(struct Scsi_Host *shost)
2153 {
2154         struct iscsi_host *ihost = shost_priv(shost);
2155
2156         kfree(ihost->netdev);
2157         kfree(ihost->hwaddress);
2158         kfree(ihost->initiatorname);
2159         scsi_host_put(shost);
2160 }
2161 EXPORT_SYMBOL_GPL(iscsi_host_free);
2162
2163 static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost)
2164 {
2165         struct iscsi_host *ihost = shost_priv(shost);
2166         unsigned long flags;
2167
2168         shost = scsi_host_get(shost);
2169         if (!shost) {
2170                 printk(KERN_ERR "Invalid state. Cannot notify host removal "
2171                       "of session teardown event because host already "
2172                       "removed.\n");
2173                 return;
2174         }
2175
2176         spin_lock_irqsave(&ihost->lock, flags);
2177         ihost->num_sessions--;
2178         if (ihost->num_sessions == 0)
2179                 wake_up(&ihost->session_removal_wq);
2180         spin_unlock_irqrestore(&ihost->lock, flags);
2181         scsi_host_put(shost);
2182 }
2183
2184 /**
2185  * iscsi_session_setup - create iscsi cls session and host and session
2186  * @iscsit: iscsi transport template
2187  * @shost: scsi host
2188  * @cmds_max: session can queue
2189  * @cmd_task_size: LLD task private data size
2190  * @initial_cmdsn: initial CmdSN
2191  *
2192  * This can be used by software iscsi_transports that allocate
2193  * a session per scsi host.
2194  *
2195  * Callers should set cmds_max to the largest total numer (mgmt + scsi) of
2196  * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
2197  * for nop handling and login/logout requests.
2198  */
2199 struct iscsi_cls_session *
2200 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
2201                     uint16_t cmds_max, int cmd_task_size,
2202                     uint32_t initial_cmdsn, unsigned int id)
2203 {
2204         struct iscsi_host *ihost = shost_priv(shost);
2205         struct iscsi_session *session;
2206         struct iscsi_cls_session *cls_session;
2207         int cmd_i, scsi_cmds, total_cmds = cmds_max;
2208         unsigned long flags;
2209
2210         spin_lock_irqsave(&ihost->lock, flags);
2211         if (ihost->state == ISCSI_HOST_REMOVED) {
2212                 spin_unlock_irqrestore(&ihost->lock, flags);
2213                 return NULL;
2214         }
2215         ihost->num_sessions++;
2216         spin_unlock_irqrestore(&ihost->lock, flags);
2217
2218         if (!total_cmds)
2219                 total_cmds = ISCSI_DEF_XMIT_CMDS_MAX;
2220         /*
2221          * The iscsi layer needs some tasks for nop handling and tmfs,
2222          * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX
2223          * + 1 command for scsi IO.
2224          */
2225         if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2226                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2227                        "must be a power of two that is at least %d.\n",
2228                        total_cmds, ISCSI_TOTAL_CMDS_MIN);
2229                 goto dec_session_count;
2230         }
2231
2232         if (total_cmds > ISCSI_TOTAL_CMDS_MAX) {
2233                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2234                        "must be a power of 2 less than or equal to %d.\n",
2235                        cmds_max, ISCSI_TOTAL_CMDS_MAX);
2236                 total_cmds = ISCSI_TOTAL_CMDS_MAX;
2237         }
2238
2239         if (!is_power_of_2(total_cmds)) {
2240                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2241                        "must be a power of 2.\n", total_cmds);
2242                 total_cmds = rounddown_pow_of_two(total_cmds);
2243                 if (total_cmds < ISCSI_TOTAL_CMDS_MIN)
2244                         return NULL;
2245                 printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n",
2246                        total_cmds);
2247         }
2248         scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX;
2249
2250         cls_session = iscsi_alloc_session(shost, iscsit,
2251                                           sizeof(struct iscsi_session));
2252         if (!cls_session)
2253                 goto dec_session_count;
2254         session = cls_session->dd_data;
2255         session->cls_session = cls_session;
2256         session->host = shost;
2257         session->state = ISCSI_STATE_FREE;
2258         session->fast_abort = 1;
2259         session->lu_reset_timeout = 15;
2260         session->abort_timeout = 10;
2261         session->scsi_cmds_max = scsi_cmds;
2262         session->cmds_max = total_cmds;
2263         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
2264         session->exp_cmdsn = initial_cmdsn + 1;
2265         session->max_cmdsn = initial_cmdsn + 1;
2266         session->max_r2t = 1;
2267         session->tt = iscsit;
2268         mutex_init(&session->eh_mutex);
2269         spin_lock_init(&session->lock);
2270
2271         /* initialize SCSI PDU commands pool */
2272         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
2273                             (void***)&session->cmds,
2274                             cmd_task_size + sizeof(struct iscsi_task)))
2275                 goto cmdpool_alloc_fail;
2276
2277         /* pre-format cmds pool with ITT */
2278         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2279                 struct iscsi_task *task = session->cmds[cmd_i];
2280
2281                 if (cmd_task_size)
2282                         task->dd_data = &task[1];
2283                 task->itt = cmd_i;
2284                 INIT_LIST_HEAD(&task->running);
2285         }
2286
2287         if (!try_module_get(iscsit->owner))
2288                 goto module_get_fail;
2289
2290         if (iscsi_add_session(cls_session, id))
2291                 goto cls_session_fail;
2292
2293         return cls_session;
2294
2295 cls_session_fail:
2296         module_put(iscsit->owner);
2297 module_get_fail:
2298         iscsi_pool_free(&session->cmdpool);
2299 cmdpool_alloc_fail:
2300         iscsi_free_session(cls_session);
2301 dec_session_count:
2302         iscsi_host_dec_session_cnt(shost);
2303         return NULL;
2304 }
2305 EXPORT_SYMBOL_GPL(iscsi_session_setup);
2306
2307 /**
2308  * iscsi_session_teardown - destroy session, host, and cls_session
2309  * @cls_session: iscsi session
2310  *
2311  * The driver must have called iscsi_remove_session before
2312  * calling this.
2313  */
2314 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
2315 {
2316         struct iscsi_session *session = cls_session->dd_data;
2317         struct module *owner = cls_session->transport->owner;
2318         struct Scsi_Host *shost = session->host;
2319
2320         iscsi_pool_free(&session->cmdpool);
2321
2322         kfree(session->password);
2323         kfree(session->password_in);
2324         kfree(session->username);
2325         kfree(session->username_in);
2326         kfree(session->targetname);
2327         kfree(session->initiatorname);
2328         kfree(session->ifacename);
2329
2330         iscsi_destroy_session(cls_session);
2331         iscsi_host_dec_session_cnt(shost);
2332         module_put(owner);
2333 }
2334 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
2335
2336 /**
2337  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
2338  * @cls_session: iscsi_cls_session
2339  * @dd_size: private driver data size
2340  * @conn_idx: cid
2341  */
2342 struct iscsi_cls_conn *
2343 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
2344                  uint32_t conn_idx)
2345 {
2346         struct iscsi_session *session = cls_session->dd_data;
2347         struct iscsi_conn *conn;
2348         struct iscsi_cls_conn *cls_conn;
2349         char *data;
2350
2351         cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
2352                                      conn_idx);
2353         if (!cls_conn)
2354                 return NULL;
2355         conn = cls_conn->dd_data;
2356         memset(conn, 0, sizeof(*conn) + dd_size);
2357
2358         conn->dd_data = cls_conn->dd_data + sizeof(*conn);
2359         conn->session = session;
2360         conn->cls_conn = cls_conn;
2361         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
2362         conn->id = conn_idx;
2363         conn->exp_statsn = 0;
2364         conn->tmf_state = TMF_INITIAL;
2365
2366         init_timer(&conn->transport_timer);
2367         conn->transport_timer.data = (unsigned long)conn;
2368         conn->transport_timer.function = iscsi_check_transport_timeouts;
2369
2370         INIT_LIST_HEAD(&conn->run_list);
2371         INIT_LIST_HEAD(&conn->mgmt_run_list);
2372         INIT_LIST_HEAD(&conn->mgmtqueue);
2373         INIT_LIST_HEAD(&conn->xmitqueue);
2374         INIT_LIST_HEAD(&conn->requeue);
2375         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
2376
2377         /* allocate login_task used for the login/text sequences */
2378         spin_lock_bh(&session->lock);
2379         if (!__kfifo_get(session->cmdpool.queue,
2380                          (void*)&conn->login_task,
2381                          sizeof(void*))) {
2382                 spin_unlock_bh(&session->lock);
2383                 goto login_task_alloc_fail;
2384         }
2385         spin_unlock_bh(&session->lock);
2386
2387         data = (char *) __get_free_pages(GFP_KERNEL,
2388                                          get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2389         if (!data)
2390                 goto login_task_data_alloc_fail;
2391         conn->login_task->data = conn->data = data;
2392
2393         init_timer(&conn->tmf_timer);
2394         init_waitqueue_head(&conn->ehwait);
2395
2396         return cls_conn;
2397
2398 login_task_data_alloc_fail:
2399         __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task,
2400                     sizeof(void*));
2401 login_task_alloc_fail:
2402         iscsi_destroy_conn(cls_conn);
2403         return NULL;
2404 }
2405 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
2406
2407 /**
2408  * iscsi_conn_teardown - teardown iscsi connection
2409  * cls_conn: iscsi class connection
2410  *
2411  * TODO: we may need to make this into a two step process
2412  * like scsi-mls remove + put host
2413  */
2414 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
2415 {
2416         struct iscsi_conn *conn = cls_conn->dd_data;
2417         struct iscsi_session *session = conn->session;
2418         unsigned long flags;
2419
2420         del_timer_sync(&conn->transport_timer);
2421
2422         spin_lock_bh(&session->lock);
2423         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
2424         if (session->leadconn == conn) {
2425                 /*
2426                  * leading connection? then give up on recovery.
2427                  */
2428                 session->state = ISCSI_STATE_TERMINATE;
2429                 wake_up(&conn->ehwait);
2430         }
2431         spin_unlock_bh(&session->lock);
2432
2433         /*
2434          * Block until all in-progress commands for this connection
2435          * time out or fail.
2436          */
2437         for (;;) {
2438                 spin_lock_irqsave(session->host->host_lock, flags);
2439                 if (!session->host->host_busy) { /* OK for ERL == 0 */
2440                         spin_unlock_irqrestore(session->host->host_lock, flags);
2441                         break;
2442                 }
2443                 spin_unlock_irqrestore(session->host->host_lock, flags);
2444                 msleep_interruptible(500);
2445                 iscsi_conn_printk(KERN_INFO, conn, "iscsi conn_destroy(): "
2446                                   "host_busy %d host_failed %d\n",
2447                                   session->host->host_busy,
2448                                   session->host->host_failed);
2449                 /*
2450                  * force eh_abort() to unblock
2451                  */
2452                 wake_up(&conn->ehwait);
2453         }
2454
2455         /* flush queued up work because we free the connection below */
2456         iscsi_suspend_tx(conn);
2457
2458         spin_lock_bh(&session->lock);
2459         free_pages((unsigned long) conn->data,
2460                    get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2461         kfree(conn->persistent_address);
2462         __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task,
2463                     sizeof(void*));
2464         if (session->leadconn == conn)
2465                 session->leadconn = NULL;
2466         spin_unlock_bh(&session->lock);
2467
2468         iscsi_destroy_conn(cls_conn);
2469 }
2470 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
2471
2472 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
2473 {
2474         struct iscsi_conn *conn = cls_conn->dd_data;
2475         struct iscsi_session *session = conn->session;
2476
2477         if (!session) {
2478                 iscsi_conn_printk(KERN_ERR, conn,
2479                                   "can't start unbound connection\n");
2480                 return -EPERM;
2481         }
2482
2483         if ((session->imm_data_en || !session->initial_r2t_en) &&
2484              session->first_burst > session->max_burst) {
2485                 iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
2486                                   "first_burst %d max_burst %d\n",
2487                                   session->first_burst, session->max_burst);
2488                 return -EINVAL;
2489         }
2490
2491         if (conn->ping_timeout && !conn->recv_timeout) {
2492                 iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
2493                                   "zero. Using 5 seconds\n.");
2494                 conn->recv_timeout = 5;
2495         }
2496
2497         if (conn->recv_timeout && !conn->ping_timeout) {
2498                 iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
2499                                   "zero. Using 5 seconds.\n");
2500                 conn->ping_timeout = 5;
2501         }
2502
2503         spin_lock_bh(&session->lock);
2504         conn->c_stage = ISCSI_CONN_STARTED;
2505         session->state = ISCSI_STATE_LOGGED_IN;
2506         session->queued_cmdsn = session->cmdsn;
2507
2508         conn->last_recv = jiffies;
2509         conn->last_ping = jiffies;
2510         if (conn->recv_timeout && conn->ping_timeout)
2511                 mod_timer(&conn->transport_timer,
2512                           jiffies + (conn->recv_timeout * HZ));
2513
2514         switch(conn->stop_stage) {
2515         case STOP_CONN_RECOVER:
2516                 /*
2517                  * unblock eh_abort() if it is blocked. re-try all
2518                  * commands after successful recovery
2519                  */
2520                 conn->stop_stage = 0;
2521                 conn->tmf_state = TMF_INITIAL;
2522                 session->age++;
2523                 if (session->age == 16)
2524                         session->age = 0;
2525                 break;
2526         case STOP_CONN_TERM:
2527                 conn->stop_stage = 0;
2528                 break;
2529         default:
2530                 break;
2531         }
2532         spin_unlock_bh(&session->lock);
2533
2534         iscsi_unblock_session(session->cls_session);
2535         wake_up(&conn->ehwait);
2536         return 0;
2537 }
2538 EXPORT_SYMBOL_GPL(iscsi_conn_start);
2539
2540 static void
2541 flush_control_queues(struct iscsi_session *session, struct iscsi_conn *conn)
2542 {
2543         struct iscsi_task *task, *tmp;
2544
2545         /* handle pending */
2546         list_for_each_entry_safe(task, tmp, &conn->mgmtqueue, running) {
2547                 ISCSI_DBG_SESSION(session, "flushing pending mgmt task "
2548                                   "itt 0x%x\n", task->itt);
2549                 /* release ref from prep task */
2550                 __iscsi_put_task(task);
2551         }
2552
2553         /* handle running */
2554         list_for_each_entry_safe(task, tmp, &conn->mgmt_run_list, running) {
2555                 ISCSI_DBG_SESSION(session, "flushing running mgmt task "
2556                                   "itt 0x%x\n", task->itt);
2557                 /* release ref from prep task */
2558                 __iscsi_put_task(task);
2559         }
2560
2561         conn->task = NULL;
2562 }
2563
2564 static void iscsi_start_session_recovery(struct iscsi_session *session,
2565                                          struct iscsi_conn *conn, int flag)
2566 {
2567         int old_stop_stage;
2568
2569         del_timer_sync(&conn->transport_timer);
2570
2571         mutex_lock(&session->eh_mutex);
2572         spin_lock_bh(&session->lock);
2573         if (conn->stop_stage == STOP_CONN_TERM) {
2574                 spin_unlock_bh(&session->lock);
2575                 mutex_unlock(&session->eh_mutex);
2576                 return;
2577         }
2578
2579         /*
2580          * When this is called for the in_login state, we only want to clean
2581          * up the login task and connection. We do not need to block and set
2582          * the recovery state again
2583          */
2584         if (flag == STOP_CONN_TERM)
2585                 session->state = ISCSI_STATE_TERMINATE;
2586         else if (conn->stop_stage != STOP_CONN_RECOVER)
2587                 session->state = ISCSI_STATE_IN_RECOVERY;
2588
2589         old_stop_stage = conn->stop_stage;
2590         conn->stop_stage = flag;
2591         conn->c_stage = ISCSI_CONN_STOPPED;
2592         spin_unlock_bh(&session->lock);
2593
2594         iscsi_suspend_tx(conn);
2595         /*
2596          * for connection level recovery we should not calculate
2597          * header digest. conn->hdr_size used for optimization
2598          * in hdr_extract() and will be re-negotiated at
2599          * set_param() time.
2600          */
2601         if (flag == STOP_CONN_RECOVER) {
2602                 conn->hdrdgst_en = 0;
2603                 conn->datadgst_en = 0;
2604                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
2605                     old_stop_stage != STOP_CONN_RECOVER) {
2606                         ISCSI_DBG_SESSION(session, "blocking session\n");
2607                         iscsi_block_session(session->cls_session);
2608                 }
2609         }
2610
2611         /*
2612          * flush queues.
2613          */
2614         spin_lock_bh(&session->lock);
2615         if (flag == STOP_CONN_RECOVER)
2616                 fail_all_commands(conn, -1, DID_TRANSPORT_DISRUPTED);
2617         else
2618                 fail_all_commands(conn, -1, DID_ERROR);
2619         flush_control_queues(session, conn);
2620         spin_unlock_bh(&session->lock);
2621         mutex_unlock(&session->eh_mutex);
2622 }
2623
2624 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
2625 {
2626         struct iscsi_conn *conn = cls_conn->dd_data;
2627         struct iscsi_session *session = conn->session;
2628
2629         switch (flag) {
2630         case STOP_CONN_RECOVER:
2631         case STOP_CONN_TERM:
2632                 iscsi_start_session_recovery(session, conn, flag);
2633                 break;
2634         default:
2635                 iscsi_conn_printk(KERN_ERR, conn,
2636                                   "invalid stop flag %d\n", flag);
2637         }
2638 }
2639 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
2640
2641 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
2642                     struct iscsi_cls_conn *cls_conn, int is_leading)
2643 {
2644         struct iscsi_session *session = cls_session->dd_data;
2645         struct iscsi_conn *conn = cls_conn->dd_data;
2646
2647         spin_lock_bh(&session->lock);
2648         if (is_leading)
2649                 session->leadconn = conn;
2650         spin_unlock_bh(&session->lock);
2651
2652         /*
2653          * Unblock xmitworker(), Login Phase will pass through.
2654          */
2655         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
2656         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
2657         return 0;
2658 }
2659 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
2660
2661 static int iscsi_switch_str_param(char **param, char *new_val_buf)
2662 {
2663         char *new_val;
2664
2665         if (*param) {
2666                 if (!strcmp(*param, new_val_buf))
2667                         return 0;
2668         }
2669
2670         new_val = kstrdup(new_val_buf, GFP_NOIO);
2671         if (!new_val)
2672                 return -ENOMEM;
2673
2674         kfree(*param);
2675         *param = new_val;
2676         return 0;
2677 }
2678
2679 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
2680                     enum iscsi_param param, char *buf, int buflen)
2681 {
2682         struct iscsi_conn *conn = cls_conn->dd_data;
2683         struct iscsi_session *session = conn->session;
2684         uint32_t value;
2685
2686         switch(param) {
2687         case ISCSI_PARAM_FAST_ABORT:
2688                 sscanf(buf, "%d", &session->fast_abort);
2689                 break;
2690         case ISCSI_PARAM_ABORT_TMO:
2691                 sscanf(buf, "%d", &session->abort_timeout);
2692                 break;
2693         case ISCSI_PARAM_LU_RESET_TMO:
2694                 sscanf(buf, "%d", &session->lu_reset_timeout);
2695                 break;
2696         case ISCSI_PARAM_PING_TMO:
2697                 sscanf(buf, "%d", &conn->ping_timeout);
2698                 break;
2699         case ISCSI_PARAM_RECV_TMO:
2700                 sscanf(buf, "%d", &conn->recv_timeout);
2701                 break;
2702         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2703                 sscanf(buf, "%d", &conn->max_recv_dlength);
2704                 break;
2705         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2706                 sscanf(buf, "%d", &conn->max_xmit_dlength);
2707                 break;
2708         case ISCSI_PARAM_HDRDGST_EN:
2709                 sscanf(buf, "%d", &conn->hdrdgst_en);
2710                 break;
2711         case ISCSI_PARAM_DATADGST_EN:
2712                 sscanf(buf, "%d", &conn->datadgst_en);
2713                 break;
2714         case ISCSI_PARAM_INITIAL_R2T_EN:
2715                 sscanf(buf, "%d", &session->initial_r2t_en);
2716                 break;
2717         case ISCSI_PARAM_MAX_R2T:
2718                 sscanf(buf, "%d", &session->max_r2t);
2719                 break;
2720         case ISCSI_PARAM_IMM_DATA_EN:
2721                 sscanf(buf, "%d", &session->imm_data_en);
2722                 break;
2723         case ISCSI_PARAM_FIRST_BURST:
2724                 sscanf(buf, "%d", &session->first_burst);
2725                 break;
2726         case ISCSI_PARAM_MAX_BURST:
2727                 sscanf(buf, "%d", &session->max_burst);
2728                 break;
2729         case ISCSI_PARAM_PDU_INORDER_EN:
2730                 sscanf(buf, "%d", &session->pdu_inorder_en);
2731                 break;
2732         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2733                 sscanf(buf, "%d", &session->dataseq_inorder_en);
2734                 break;
2735         case ISCSI_PARAM_ERL:
2736                 sscanf(buf, "%d", &session->erl);
2737                 break;
2738         case ISCSI_PARAM_IFMARKER_EN:
2739                 sscanf(buf, "%d", &value);
2740                 BUG_ON(value);
2741                 break;
2742         case ISCSI_PARAM_OFMARKER_EN:
2743                 sscanf(buf, "%d", &value);
2744                 BUG_ON(value);
2745                 break;
2746         case ISCSI_PARAM_EXP_STATSN:
2747                 sscanf(buf, "%u", &conn->exp_statsn);
2748                 break;
2749         case ISCSI_PARAM_USERNAME:
2750                 return iscsi_switch_str_param(&session->username, buf);
2751         case ISCSI_PARAM_USERNAME_IN:
2752                 return iscsi_switch_str_param(&session->username_in, buf);
2753         case ISCSI_PARAM_PASSWORD:
2754                 return iscsi_switch_str_param(&session->password, buf);
2755         case ISCSI_PARAM_PASSWORD_IN:
2756                 return iscsi_switch_str_param(&session->password_in, buf);
2757         case ISCSI_PARAM_TARGET_NAME:
2758                 return iscsi_switch_str_param(&session->targetname, buf);
2759         case ISCSI_PARAM_TPGT:
2760                 sscanf(buf, "%d", &session->tpgt);
2761                 break;
2762         case ISCSI_PARAM_PERSISTENT_PORT:
2763                 sscanf(buf, "%d", &conn->persistent_port);
2764                 break;
2765         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2766                 return iscsi_switch_str_param(&conn->persistent_address, buf);
2767         case ISCSI_PARAM_IFACE_NAME:
2768                 return iscsi_switch_str_param(&session->ifacename, buf);
2769         case ISCSI_PARAM_INITIATOR_NAME:
2770                 return iscsi_switch_str_param(&session->initiatorname, buf);
2771         default:
2772                 return -ENOSYS;
2773         }
2774
2775         return 0;
2776 }
2777 EXPORT_SYMBOL_GPL(iscsi_set_param);
2778
2779 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
2780                             enum iscsi_param param, char *buf)
2781 {
2782         struct iscsi_session *session = cls_session->dd_data;
2783         int len;
2784
2785         switch(param) {
2786         case ISCSI_PARAM_FAST_ABORT:
2787                 len = sprintf(buf, "%d\n", session->fast_abort);
2788                 break;
2789         case ISCSI_PARAM_ABORT_TMO:
2790                 len = sprintf(buf, "%d\n", session->abort_timeout);
2791                 break;
2792         case ISCSI_PARAM_LU_RESET_TMO:
2793                 len = sprintf(buf, "%d\n", session->lu_reset_timeout);
2794                 break;
2795         case ISCSI_PARAM_INITIAL_R2T_EN:
2796                 len = sprintf(buf, "%d\n", session->initial_r2t_en);
2797                 break;
2798         case ISCSI_PARAM_MAX_R2T:
2799                 len = sprintf(buf, "%hu\n", session->max_r2t);
2800                 break;
2801         case ISCSI_PARAM_IMM_DATA_EN:
2802                 len = sprintf(buf, "%d\n", session->imm_data_en);
2803                 break;
2804         case ISCSI_PARAM_FIRST_BURST:
2805                 len = sprintf(buf, "%u\n", session->first_burst);
2806                 break;
2807         case ISCSI_PARAM_MAX_BURST:
2808                 len = sprintf(buf, "%u\n", session->max_burst);
2809                 break;
2810         case ISCSI_PARAM_PDU_INORDER_EN:
2811                 len = sprintf(buf, "%d\n", session->pdu_inorder_en);
2812                 break;
2813         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2814                 len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
2815                 break;
2816         case ISCSI_PARAM_ERL:
2817                 len = sprintf(buf, "%d\n", session->erl);
2818                 break;
2819         case ISCSI_PARAM_TARGET_NAME:
2820                 len = sprintf(buf, "%s\n", session->targetname);
2821                 break;
2822         case ISCSI_PARAM_TPGT:
2823                 len = sprintf(buf, "%d\n", session->tpgt);
2824                 break;
2825         case ISCSI_PARAM_USERNAME:
2826                 len = sprintf(buf, "%s\n", session->username);
2827                 break;
2828         case ISCSI_PARAM_USERNAME_IN:
2829                 len = sprintf(buf, "%s\n", session->username_in);
2830                 break;
2831         case ISCSI_PARAM_PASSWORD:
2832                 len = sprintf(buf, "%s\n", session->password);
2833                 break;
2834         case ISCSI_PARAM_PASSWORD_IN:
2835                 len = sprintf(buf, "%s\n", session->password_in);
2836                 break;
2837         case ISCSI_PARAM_IFACE_NAME:
2838                 len = sprintf(buf, "%s\n", session->ifacename);
2839                 break;
2840         case ISCSI_PARAM_INITIATOR_NAME:
2841                 len = sprintf(buf, "%s\n", session->initiatorname);
2842                 break;
2843         default:
2844                 return -ENOSYS;
2845         }
2846
2847         return len;
2848 }
2849 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
2850
2851 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
2852                          enum iscsi_param param, char *buf)
2853 {
2854         struct iscsi_conn *conn = cls_conn->dd_data;
2855         int len;
2856
2857         switch(param) {
2858         case ISCSI_PARAM_PING_TMO:
2859                 len = sprintf(buf, "%u\n", conn->ping_timeout);
2860                 break;
2861         case ISCSI_PARAM_RECV_TMO:
2862                 len = sprintf(buf, "%u\n", conn->recv_timeout);
2863                 break;
2864         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2865                 len = sprintf(buf, "%u\n", conn->max_recv_dlength);
2866                 break;
2867         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2868                 len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
2869                 break;
2870         case ISCSI_PARAM_HDRDGST_EN:
2871                 len = sprintf(buf, "%d\n", conn->hdrdgst_en);
2872                 break;
2873         case ISCSI_PARAM_DATADGST_EN:
2874                 len = sprintf(buf, "%d\n", conn->datadgst_en);
2875                 break;
2876         case ISCSI_PARAM_IFMARKER_EN:
2877                 len = sprintf(buf, "%d\n", conn->ifmarker_en);
2878                 break;
2879         case ISCSI_PARAM_OFMARKER_EN:
2880                 len = sprintf(buf, "%d\n", conn->ofmarker_en);
2881                 break;
2882         case ISCSI_PARAM_EXP_STATSN:
2883                 len = sprintf(buf, "%u\n", conn->exp_statsn);
2884                 break;
2885         case ISCSI_PARAM_PERSISTENT_PORT:
2886                 len = sprintf(buf, "%d\n", conn->persistent_port);
2887                 break;
2888         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2889                 len = sprintf(buf, "%s\n", conn->persistent_address);
2890                 break;
2891         default:
2892                 return -ENOSYS;
2893         }
2894
2895         return len;
2896 }
2897 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
2898
2899 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2900                          char *buf)
2901 {
2902         struct iscsi_host *ihost = shost_priv(shost);
2903         int len;
2904
2905         switch (param) {
2906         case ISCSI_HOST_PARAM_NETDEV_NAME:
2907                 len = sprintf(buf, "%s\n", ihost->netdev);
2908                 break;
2909         case ISCSI_HOST_PARAM_HWADDRESS:
2910                 len = sprintf(buf, "%s\n", ihost->hwaddress);
2911                 break;
2912         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2913                 len = sprintf(buf, "%s\n", ihost->initiatorname);
2914                 break;
2915         case ISCSI_HOST_PARAM_IPADDRESS:
2916                 len = sprintf(buf, "%s\n", ihost->local_address);
2917                 break;
2918         default:
2919                 return -ENOSYS;
2920         }
2921
2922         return len;
2923 }
2924 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
2925
2926 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2927                          char *buf, int buflen)
2928 {
2929         struct iscsi_host *ihost = shost_priv(shost);
2930
2931         switch (param) {
2932         case ISCSI_HOST_PARAM_NETDEV_NAME:
2933                 return iscsi_switch_str_param(&ihost->netdev, buf);
2934         case ISCSI_HOST_PARAM_HWADDRESS:
2935                 return iscsi_switch_str_param(&ihost->hwaddress, buf);
2936         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2937                 return iscsi_switch_str_param(&ihost->initiatorname, buf);
2938         default:
2939                 return -ENOSYS;
2940         }
2941
2942         return 0;
2943 }
2944 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
2945
2946 MODULE_AUTHOR("Mike Christie");
2947 MODULE_DESCRIPTION("iSCSI library functions");
2948 MODULE_LICENSE("GPL");