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