[SCSI] iscsi_tcp: fix fd leak
[safe/jmp/linux-2.6] / drivers / scsi / iscsi_tcp.c
1 /*
2  * iSCSI Initiator over TCP/IP Data-Path
3  *
4  * Copyright (C) 2004 Dmitry Yusupov
5  * Copyright (C) 2004 Alex Aizman
6  * Copyright (C) 2005 - 2006 Mike Christie
7  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
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
12  * by 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, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * See the file COPYING included with this distribution for more details.
21  *
22  * Credits:
23  *      Christoph Hellwig
24  *      FUJITA Tomonori
25  *      Arne Redlich
26  *      Zhenyu Wang
27  */
28
29 #include <linux/types.h>
30 #include <linux/list.h>
31 #include <linux/inet.h>
32 #include <linux/file.h>
33 #include <linux/blkdev.h>
34 #include <linux/crypto.h>
35 #include <linux/delay.h>
36 #include <linux/kfifo.h>
37 #include <linux/scatterlist.h>
38 #include <net/tcp.h>
39 #include <scsi/scsi_cmnd.h>
40 #include <scsi/scsi_device.h>
41 #include <scsi/scsi_host.h>
42 #include <scsi/scsi.h>
43 #include <scsi/scsi_transport_iscsi.h>
44
45 #include "iscsi_tcp.h"
46
47 MODULE_AUTHOR("Dmitry Yusupov <dmitry_yus@yahoo.com>, "
48               "Alex Aizman <itn780@yahoo.com>");
49 MODULE_DESCRIPTION("iSCSI/TCP data-path");
50 MODULE_LICENSE("GPL");
51 /* #define DEBUG_TCP */
52 #define DEBUG_ASSERT
53
54 #ifdef DEBUG_TCP
55 #define debug_tcp(fmt...) printk(KERN_INFO "tcp: " fmt)
56 #else
57 #define debug_tcp(fmt...)
58 #endif
59
60 #ifndef DEBUG_ASSERT
61 #ifdef BUG_ON
62 #undef BUG_ON
63 #endif
64 #define BUG_ON(expr)
65 #endif
66
67 static unsigned int iscsi_max_lun = 512;
68 module_param_named(max_lun, iscsi_max_lun, uint, S_IRUGO);
69
70 static inline void
71 iscsi_buf_init_iov(struct iscsi_buf *ibuf, char *vbuf, int size)
72 {
73         ibuf->sg.page = virt_to_page(vbuf);
74         ibuf->sg.offset = offset_in_page(vbuf);
75         ibuf->sg.length = size;
76         ibuf->sent = 0;
77         ibuf->use_sendmsg = 1;
78 }
79
80 static inline void
81 iscsi_buf_init_sg(struct iscsi_buf *ibuf, struct scatterlist *sg)
82 {
83         ibuf->sg.page = sg->page;
84         ibuf->sg.offset = sg->offset;
85         ibuf->sg.length = sg->length;
86         /*
87          * Fastpath: sg element fits into single page
88          */
89         if (sg->length + sg->offset <= PAGE_SIZE && !PageSlab(sg->page))
90                 ibuf->use_sendmsg = 0;
91         else
92                 ibuf->use_sendmsg = 1;
93         ibuf->sent = 0;
94 }
95
96 static inline int
97 iscsi_buf_left(struct iscsi_buf *ibuf)
98 {
99         int rc;
100
101         rc = ibuf->sg.length - ibuf->sent;
102         BUG_ON(rc < 0);
103         return rc;
104 }
105
106 static inline void
107 iscsi_hdr_digest(struct iscsi_conn *conn, struct iscsi_buf *buf,
108                  u8* crc)
109 {
110         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
111
112         crypto_hash_digest(&tcp_conn->tx_hash, &buf->sg, buf->sg.length, crc);
113         buf->sg.length += sizeof(u32);
114 }
115
116 static inline int
117 iscsi_hdr_extract(struct iscsi_tcp_conn *tcp_conn)
118 {
119         struct sk_buff *skb = tcp_conn->in.skb;
120
121         tcp_conn->in.zero_copy_hdr = 0;
122
123         if (tcp_conn->in.copy >= tcp_conn->hdr_size &&
124             tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER) {
125                 /*
126                  * Zero-copy PDU Header: using connection context
127                  * to store header pointer.
128                  */
129                 if (skb_shinfo(skb)->frag_list == NULL &&
130                     !skb_shinfo(skb)->nr_frags) {
131                         tcp_conn->in.hdr = (struct iscsi_hdr *)
132                                 ((char*)skb->data + tcp_conn->in.offset);
133                         tcp_conn->in.zero_copy_hdr = 1;
134                 } else {
135                         /* ignoring return code since we checked
136                          * in.copy before */
137                         skb_copy_bits(skb, tcp_conn->in.offset,
138                                 &tcp_conn->hdr, tcp_conn->hdr_size);
139                         tcp_conn->in.hdr = &tcp_conn->hdr;
140                 }
141                 tcp_conn->in.offset += tcp_conn->hdr_size;
142                 tcp_conn->in.copy -= tcp_conn->hdr_size;
143         } else {
144                 int hdr_remains;
145                 int copylen;
146
147                 /*
148                  * PDU header scattered across SKB's,
149                  * copying it... This'll happen quite rarely.
150                  */
151
152                 if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER)
153                         tcp_conn->in.hdr_offset = 0;
154
155                 hdr_remains = tcp_conn->hdr_size - tcp_conn->in.hdr_offset;
156                 BUG_ON(hdr_remains <= 0);
157
158                 copylen = min(tcp_conn->in.copy, hdr_remains);
159                 skb_copy_bits(skb, tcp_conn->in.offset,
160                         (char*)&tcp_conn->hdr + tcp_conn->in.hdr_offset,
161                         copylen);
162
163                 debug_tcp("PDU gather offset %d bytes %d in.offset %d "
164                        "in.copy %d\n", tcp_conn->in.hdr_offset, copylen,
165                        tcp_conn->in.offset, tcp_conn->in.copy);
166
167                 tcp_conn->in.offset += copylen;
168                 tcp_conn->in.copy -= copylen;
169                 if (copylen < hdr_remains)  {
170                         tcp_conn->in_progress = IN_PROGRESS_HEADER_GATHER;
171                         tcp_conn->in.hdr_offset += copylen;
172                         return -EAGAIN;
173                 }
174                 tcp_conn->in.hdr = &tcp_conn->hdr;
175                 tcp_conn->discontiguous_hdr_cnt++;
176                 tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
177         }
178
179         return 0;
180 }
181
182 /*
183  * must be called with session lock
184  */
185 static void
186 iscsi_tcp_cleanup_ctask(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
187 {
188         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
189         struct iscsi_r2t_info *r2t;
190         struct scsi_cmnd *sc;
191
192         /* flush ctask's r2t queues */
193         while (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*))) {
194                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
195                             sizeof(void*));
196                 debug_scsi("iscsi_tcp_cleanup_ctask pending r2t dropped\n");
197         }
198
199         sc = ctask->sc;
200         if (unlikely(!sc))
201                 return;
202
203         tcp_ctask->xmstate = XMSTATE_IDLE;
204         tcp_ctask->r2t = NULL;
205 }
206
207 /**
208  * iscsi_data_rsp - SCSI Data-In Response processing
209  * @conn: iscsi connection
210  * @ctask: scsi command task
211  **/
212 static int
213 iscsi_data_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
214 {
215         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
216         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
217         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr;
218         struct iscsi_session *session = conn->session;
219         struct scsi_cmnd *sc = ctask->sc;
220         int datasn = be32_to_cpu(rhdr->datasn);
221
222         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
223         /*
224          * setup Data-In byte counter (gets decremented..)
225          */
226         ctask->data_count = tcp_conn->in.datalen;
227
228         if (tcp_conn->in.datalen == 0)
229                 return 0;
230
231         if (tcp_ctask->exp_datasn != datasn) {
232                 debug_tcp("%s: ctask->exp_datasn(%d) != rhdr->datasn(%d)\n",
233                           __FUNCTION__, tcp_ctask->exp_datasn, datasn);
234                 return ISCSI_ERR_DATASN;
235         }
236
237         tcp_ctask->exp_datasn++;
238
239         tcp_ctask->data_offset = be32_to_cpu(rhdr->offset);
240         if (tcp_ctask->data_offset + tcp_conn->in.datalen > sc->request_bufflen) {
241                 debug_tcp("%s: data_offset(%d) + data_len(%d) > total_length_in(%d)\n",
242                           __FUNCTION__, tcp_ctask->data_offset,
243                           tcp_conn->in.datalen, sc->request_bufflen);
244                 return ISCSI_ERR_DATA_OFFSET;
245         }
246
247         if (rhdr->flags & ISCSI_FLAG_DATA_STATUS) {
248                 conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
249                 if (rhdr->flags & ISCSI_FLAG_DATA_UNDERFLOW) {
250                         int res_count = be32_to_cpu(rhdr->residual_count);
251
252                         if (res_count > 0 &&
253                             res_count <= sc->request_bufflen) {
254                                 sc->resid = res_count;
255                                 sc->result = (DID_OK << 16) | rhdr->cmd_status;
256                         } else
257                                 sc->result = (DID_BAD_TARGET << 16) |
258                                         rhdr->cmd_status;
259                 } else if (rhdr->flags & ISCSI_FLAG_DATA_OVERFLOW) {
260                         sc->resid = be32_to_cpu(rhdr->residual_count);
261                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
262                 } else
263                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
264         }
265
266         conn->datain_pdus_cnt++;
267         return 0;
268 }
269
270 /**
271  * iscsi_solicit_data_init - initialize first Data-Out
272  * @conn: iscsi connection
273  * @ctask: scsi command task
274  * @r2t: R2T info
275  *
276  * Notes:
277  *      Initialize first Data-Out within this R2T sequence and finds
278  *      proper data_offset within this SCSI command.
279  *
280  *      This function is called with connection lock taken.
281  **/
282 static void
283 iscsi_solicit_data_init(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
284                         struct iscsi_r2t_info *r2t)
285 {
286         struct iscsi_data *hdr;
287         struct scsi_cmnd *sc = ctask->sc;
288
289         hdr = &r2t->dtask.hdr;
290         memset(hdr, 0, sizeof(struct iscsi_data));
291         hdr->ttt = r2t->ttt;
292         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
293         r2t->solicit_datasn++;
294         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
295         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
296         hdr->itt = ctask->hdr->itt;
297         hdr->exp_statsn = r2t->exp_statsn;
298         hdr->offset = cpu_to_be32(r2t->data_offset);
299         if (r2t->data_length > conn->max_xmit_dlength) {
300                 hton24(hdr->dlength, conn->max_xmit_dlength);
301                 r2t->data_count = conn->max_xmit_dlength;
302                 hdr->flags = 0;
303         } else {
304                 hton24(hdr->dlength, r2t->data_length);
305                 r2t->data_count = r2t->data_length;
306                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
307         }
308         conn->dataout_pdus_cnt++;
309
310         r2t->sent = 0;
311
312         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
313                            sizeof(struct iscsi_hdr));
314
315         if (sc->use_sg) {
316                 int i, sg_count = 0;
317                 struct scatterlist *sg = sc->request_buffer;
318
319                 r2t->sg = NULL;
320                 for (i = 0; i < sc->use_sg; i++, sg += 1) {
321                         /* FIXME: prefetch ? */
322                         if (sg_count + sg->length > r2t->data_offset) {
323                                 int page_offset;
324
325                                 /* sg page found! */
326
327                                 /* offset within this page */
328                                 page_offset = r2t->data_offset - sg_count;
329
330                                 /* fill in this buffer */
331                                 iscsi_buf_init_sg(&r2t->sendbuf, sg);
332                                 r2t->sendbuf.sg.offset += page_offset;
333                                 r2t->sendbuf.sg.length -= page_offset;
334
335                                 /* xmit logic will continue with next one */
336                                 r2t->sg = sg + 1;
337                                 break;
338                         }
339                         sg_count += sg->length;
340                 }
341                 BUG_ON(r2t->sg == NULL);
342         } else {
343                 iscsi_buf_init_iov(&r2t->sendbuf,
344                             (char*)sc->request_buffer + r2t->data_offset,
345                             r2t->data_count);
346                 r2t->sg = NULL;
347         }
348 }
349
350 /**
351  * iscsi_r2t_rsp - iSCSI R2T Response processing
352  * @conn: iscsi connection
353  * @ctask: scsi command task
354  **/
355 static int
356 iscsi_r2t_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
357 {
358         struct iscsi_r2t_info *r2t;
359         struct iscsi_session *session = conn->session;
360         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
361         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
362         struct iscsi_r2t_rsp *rhdr = (struct iscsi_r2t_rsp *)tcp_conn->in.hdr;
363         int r2tsn = be32_to_cpu(rhdr->r2tsn);
364         int rc;
365
366         if (tcp_conn->in.datalen) {
367                 printk(KERN_ERR "iscsi_tcp: invalid R2t with datalen %d\n",
368                        tcp_conn->in.datalen);
369                 return ISCSI_ERR_DATALEN;
370         }
371
372         if (tcp_ctask->exp_datasn != r2tsn){
373                 debug_tcp("%s: ctask->exp_datasn(%d) != rhdr->r2tsn(%d)\n",
374                           __FUNCTION__, tcp_ctask->exp_datasn, r2tsn);
375                 return ISCSI_ERR_R2TSN;
376         }
377
378         /* fill-in new R2T associated with the task */
379         spin_lock(&session->lock);
380         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
381
382         if (!ctask->sc || ctask->mtask ||
383              session->state != ISCSI_STATE_LOGGED_IN) {
384                 printk(KERN_INFO "iscsi_tcp: dropping R2T itt %d in "
385                        "recovery...\n", ctask->itt);
386                 spin_unlock(&session->lock);
387                 return 0;
388         }
389
390         rc = __kfifo_get(tcp_ctask->r2tpool.queue, (void*)&r2t, sizeof(void*));
391         BUG_ON(!rc);
392
393         r2t->exp_statsn = rhdr->statsn;
394         r2t->data_length = be32_to_cpu(rhdr->data_length);
395         if (r2t->data_length == 0) {
396                 printk(KERN_ERR "iscsi_tcp: invalid R2T with zero data len\n");
397                 spin_unlock(&session->lock);
398                 return ISCSI_ERR_DATALEN;
399         }
400
401         if (r2t->data_length > session->max_burst)
402                 debug_scsi("invalid R2T with data len %u and max burst %u."
403                            "Attempting to execute request.\n",
404                             r2t->data_length, session->max_burst);
405
406         r2t->data_offset = be32_to_cpu(rhdr->data_offset);
407         if (r2t->data_offset + r2t->data_length > ctask->sc->request_bufflen) {
408                 spin_unlock(&session->lock);
409                 printk(KERN_ERR "iscsi_tcp: invalid R2T with data len %u at "
410                        "offset %u and total length %d\n", r2t->data_length,
411                        r2t->data_offset, ctask->sc->request_bufflen);
412                 return ISCSI_ERR_DATALEN;
413         }
414
415         r2t->ttt = rhdr->ttt; /* no flip */
416         r2t->solicit_datasn = 0;
417
418         iscsi_solicit_data_init(conn, ctask, r2t);
419
420         tcp_ctask->exp_datasn = r2tsn + 1;
421         __kfifo_put(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*));
422         tcp_ctask->xmstate |= XMSTATE_SOL_HDR_INIT;
423         list_move_tail(&ctask->running, &conn->xmitqueue);
424
425         scsi_queue_work(session->host, &conn->xmitwork);
426         conn->r2t_pdus_cnt++;
427         spin_unlock(&session->lock);
428
429         return 0;
430 }
431
432 static int
433 iscsi_tcp_hdr_recv(struct iscsi_conn *conn)
434 {
435         int rc = 0, opcode, ahslen;
436         struct iscsi_hdr *hdr;
437         struct iscsi_session *session = conn->session;
438         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
439         uint32_t cdgst, rdgst = 0, itt;
440
441         hdr = tcp_conn->in.hdr;
442
443         /* verify PDU length */
444         tcp_conn->in.datalen = ntoh24(hdr->dlength);
445         if (tcp_conn->in.datalen > conn->max_recv_dlength) {
446                 printk(KERN_ERR "iscsi_tcp: datalen %d > %d\n",
447                        tcp_conn->in.datalen, conn->max_recv_dlength);
448                 return ISCSI_ERR_DATALEN;
449         }
450         tcp_conn->data_copied = 0;
451
452         /* read AHS */
453         ahslen = hdr->hlength << 2;
454         tcp_conn->in.offset += ahslen;
455         tcp_conn->in.copy -= ahslen;
456         if (tcp_conn->in.copy < 0) {
457                 printk(KERN_ERR "iscsi_tcp: can't handle AHS with length "
458                        "%d bytes\n", ahslen);
459                 return ISCSI_ERR_AHSLEN;
460         }
461
462         /* calculate read padding */
463         tcp_conn->in.padding = tcp_conn->in.datalen & (ISCSI_PAD_LEN-1);
464         if (tcp_conn->in.padding) {
465                 tcp_conn->in.padding = ISCSI_PAD_LEN - tcp_conn->in.padding;
466                 debug_scsi("read padding %d bytes\n", tcp_conn->in.padding);
467         }
468
469         if (conn->hdrdgst_en) {
470                 struct scatterlist sg;
471
472                 sg_init_one(&sg, (u8 *)hdr,
473                             sizeof(struct iscsi_hdr) + ahslen);
474                 crypto_hash_digest(&tcp_conn->rx_hash, &sg, sg.length,
475                                    (u8 *)&cdgst);
476                 rdgst = *(uint32_t*)((char*)hdr + sizeof(struct iscsi_hdr) +
477                                      ahslen);
478                 if (cdgst != rdgst) {
479                         printk(KERN_ERR "iscsi_tcp: hdrdgst error "
480                                "recv 0x%x calc 0x%x\n", rdgst, cdgst);
481                         return ISCSI_ERR_HDR_DGST;
482                 }
483         }
484
485         opcode = hdr->opcode & ISCSI_OPCODE_MASK;
486         /* verify itt (itt encoding: age+cid+itt) */
487         rc = iscsi_verify_itt(conn, hdr, &itt);
488         if (rc == ISCSI_ERR_NO_SCSI_CMD) {
489                 tcp_conn->in.datalen = 0; /* force drop */
490                 return 0;
491         } else if (rc)
492                 return rc;
493
494         debug_tcp("opcode 0x%x offset %d copy %d ahslen %d datalen %d\n",
495                   opcode, tcp_conn->in.offset, tcp_conn->in.copy,
496                   ahslen, tcp_conn->in.datalen);
497
498         switch(opcode) {
499         case ISCSI_OP_SCSI_DATA_IN:
500                 tcp_conn->in.ctask = session->cmds[itt];
501                 rc = iscsi_data_rsp(conn, tcp_conn->in.ctask);
502                 if (rc)
503                         return rc;
504                 /* fall through */
505         case ISCSI_OP_SCSI_CMD_RSP:
506                 tcp_conn->in.ctask = session->cmds[itt];
507                 if (tcp_conn->in.datalen)
508                         goto copy_hdr;
509
510                 spin_lock(&session->lock);
511                 rc = __iscsi_complete_pdu(conn, hdr, NULL, 0);
512                 spin_unlock(&session->lock);
513                 break;
514         case ISCSI_OP_R2T:
515                 tcp_conn->in.ctask = session->cmds[itt];
516                 if (ahslen)
517                         rc = ISCSI_ERR_AHSLEN;
518                 else if (tcp_conn->in.ctask->sc->sc_data_direction ==
519                                                                 DMA_TO_DEVICE)
520                         rc = iscsi_r2t_rsp(conn, tcp_conn->in.ctask);
521                 else
522                         rc = ISCSI_ERR_PROTO;
523                 break;
524         case ISCSI_OP_LOGIN_RSP:
525         case ISCSI_OP_TEXT_RSP:
526         case ISCSI_OP_REJECT:
527         case ISCSI_OP_ASYNC_EVENT:
528                 /*
529                  * It is possible that we could get a PDU with a buffer larger
530                  * than 8K, but there are no targets that currently do this.
531                  * For now we fail until we find a vendor that needs it
532                  */
533                 if (ISCSI_DEF_MAX_RECV_SEG_LEN <
534                     tcp_conn->in.datalen) {
535                         printk(KERN_ERR "iscsi_tcp: received buffer of len %u "
536                               "but conn buffer is only %u (opcode %0x)\n",
537                               tcp_conn->in.datalen,
538                               ISCSI_DEF_MAX_RECV_SEG_LEN, opcode);
539                         rc = ISCSI_ERR_PROTO;
540                         break;
541                 }
542
543                 if (tcp_conn->in.datalen)
544                         goto copy_hdr;
545         /* fall through */
546         case ISCSI_OP_LOGOUT_RSP:
547         case ISCSI_OP_NOOP_IN:
548         case ISCSI_OP_SCSI_TMFUNC_RSP:
549                 rc = iscsi_complete_pdu(conn, hdr, NULL, 0);
550                 break;
551         default:
552                 rc = ISCSI_ERR_BAD_OPCODE;
553                 break;
554         }
555
556         return rc;
557
558 copy_hdr:
559         /*
560          * if we did zero copy for the header but we will need multiple
561          * skbs to complete the command then we have to copy the header
562          * for later use
563          */
564         if (tcp_conn->in.zero_copy_hdr && tcp_conn->in.copy <=
565            (tcp_conn->in.datalen + tcp_conn->in.padding +
566             (conn->datadgst_en ? 4 : 0))) {
567                 debug_tcp("Copying header for later use. in.copy %d in.datalen"
568                           " %d\n", tcp_conn->in.copy, tcp_conn->in.datalen);
569                 memcpy(&tcp_conn->hdr, tcp_conn->in.hdr,
570                        sizeof(struct iscsi_hdr));
571                 tcp_conn->in.hdr = &tcp_conn->hdr;
572                 tcp_conn->in.zero_copy_hdr = 0;
573         }
574         return 0;
575 }
576
577 /**
578  * iscsi_ctask_copy - copy skb bits to the destanation cmd task
579  * @conn: iscsi tcp connection
580  * @ctask: scsi command task
581  * @buf: buffer to copy to
582  * @buf_size: size of buffer
583  * @offset: offset within the buffer
584  *
585  * Notes:
586  *      The function calls skb_copy_bits() and updates per-connection and
587  *      per-cmd byte counters.
588  *
589  *      Read counters (in bytes):
590  *
591  *      conn->in.offset         offset within in progress SKB
592  *      conn->in.copy           left to copy from in progress SKB
593  *                              including padding
594  *      conn->in.copied         copied already from in progress SKB
595  *      conn->data_copied       copied already from in progress buffer
596  *      ctask->sent             total bytes sent up to the MidLayer
597  *      ctask->data_count       left to copy from in progress Data-In
598  *      buf_left                left to copy from in progress buffer
599  **/
600 static inline int
601 iscsi_ctask_copy(struct iscsi_tcp_conn *tcp_conn, struct iscsi_cmd_task *ctask,
602                 void *buf, int buf_size, int offset)
603 {
604         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
605         int buf_left = buf_size - (tcp_conn->data_copied + offset);
606         unsigned size = min(tcp_conn->in.copy, buf_left);
607         int rc;
608
609         size = min(size, ctask->data_count);
610
611         debug_tcp("ctask_copy %d bytes at offset %d copied %d\n",
612                size, tcp_conn->in.offset, tcp_conn->in.copied);
613
614         BUG_ON(size <= 0);
615         BUG_ON(tcp_ctask->sent + size > ctask->sc->request_bufflen);
616
617         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
618                            (char*)buf + (offset + tcp_conn->data_copied), size);
619         /* must fit into skb->len */
620         BUG_ON(rc);
621
622         tcp_conn->in.offset += size;
623         tcp_conn->in.copy -= size;
624         tcp_conn->in.copied += size;
625         tcp_conn->data_copied += size;
626         tcp_ctask->sent += size;
627         ctask->data_count -= size;
628
629         BUG_ON(tcp_conn->in.copy < 0);
630         BUG_ON(ctask->data_count < 0);
631
632         if (buf_size != (tcp_conn->data_copied + offset)) {
633                 if (!ctask->data_count) {
634                         BUG_ON(buf_size - tcp_conn->data_copied < 0);
635                         /* done with this PDU */
636                         return buf_size - tcp_conn->data_copied;
637                 }
638                 return -EAGAIN;
639         }
640
641         /* done with this buffer or with both - PDU and buffer */
642         tcp_conn->data_copied = 0;
643         return 0;
644 }
645
646 /**
647  * iscsi_tcp_copy - copy skb bits to the destanation buffer
648  * @conn: iscsi tcp connection
649  *
650  * Notes:
651  *      The function calls skb_copy_bits() and updates per-connection
652  *      byte counters.
653  **/
654 static inline int
655 iscsi_tcp_copy(struct iscsi_conn *conn, int buf_size)
656 {
657         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
658         int buf_left = buf_size - tcp_conn->data_copied;
659         int size = min(tcp_conn->in.copy, buf_left);
660         int rc;
661
662         debug_tcp("tcp_copy %d bytes at offset %d copied %d\n",
663                size, tcp_conn->in.offset, tcp_conn->data_copied);
664         BUG_ON(size <= 0);
665
666         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
667                            (char*)conn->data + tcp_conn->data_copied, size);
668         BUG_ON(rc);
669
670         tcp_conn->in.offset += size;
671         tcp_conn->in.copy -= size;
672         tcp_conn->in.copied += size;
673         tcp_conn->data_copied += size;
674
675         if (buf_size != tcp_conn->data_copied)
676                 return -EAGAIN;
677
678         return 0;
679 }
680
681 static inline void
682 partial_sg_digest_update(struct hash_desc *desc, struct scatterlist *sg,
683                          int offset, int length)
684 {
685         struct scatterlist temp;
686
687         memcpy(&temp, sg, sizeof(struct scatterlist));
688         temp.offset = offset;
689         temp.length = length;
690         crypto_hash_update(desc, &temp, length);
691 }
692
693 static void
694 iscsi_recv_digest_update(struct iscsi_tcp_conn *tcp_conn, char* buf, int len)
695 {
696         struct scatterlist tmp;
697
698         sg_init_one(&tmp, buf, len);
699         crypto_hash_update(&tcp_conn->rx_hash, &tmp, len);
700 }
701
702 static int iscsi_scsi_data_in(struct iscsi_conn *conn)
703 {
704         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
705         struct iscsi_cmd_task *ctask = tcp_conn->in.ctask;
706         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
707         struct scsi_cmnd *sc = ctask->sc;
708         struct scatterlist *sg;
709         int i, offset, rc = 0;
710
711         BUG_ON((void*)ctask != sc->SCp.ptr);
712
713         /*
714          * copying Data-In into the Scsi_Cmnd
715          */
716         if (!sc->use_sg) {
717                 i = ctask->data_count;
718                 rc = iscsi_ctask_copy(tcp_conn, ctask, sc->request_buffer,
719                                       sc->request_bufflen,
720                                       tcp_ctask->data_offset);
721                 if (rc == -EAGAIN)
722                         return rc;
723                 if (conn->datadgst_en)
724                         iscsi_recv_digest_update(tcp_conn, sc->request_buffer,
725                                                  i);
726                 rc = 0;
727                 goto done;
728         }
729
730         offset = tcp_ctask->data_offset;
731         sg = sc->request_buffer;
732
733         if (tcp_ctask->data_offset)
734                 for (i = 0; i < tcp_ctask->sg_count; i++)
735                         offset -= sg[i].length;
736         /* we've passed through partial sg*/
737         if (offset < 0)
738                 offset = 0;
739
740         for (i = tcp_ctask->sg_count; i < sc->use_sg; i++) {
741                 char *dest;
742
743                 dest = kmap_atomic(sg[i].page, KM_SOFTIRQ0);
744                 rc = iscsi_ctask_copy(tcp_conn, ctask, dest + sg[i].offset,
745                                       sg[i].length, offset);
746                 kunmap_atomic(dest, KM_SOFTIRQ0);
747                 if (rc == -EAGAIN)
748                         /* continue with the next SKB/PDU */
749                         return rc;
750                 if (!rc) {
751                         if (conn->datadgst_en) {
752                                 if (!offset)
753                                         crypto_hash_update(
754                                                         &tcp_conn->rx_hash,
755                                                         &sg[i], sg[i].length);
756                                 else
757                                         partial_sg_digest_update(
758                                                         &tcp_conn->rx_hash,
759                                                         &sg[i],
760                                                         sg[i].offset + offset,
761                                                         sg[i].length - offset);
762                         }
763                         offset = 0;
764                         tcp_ctask->sg_count++;
765                 }
766
767                 if (!ctask->data_count) {
768                         if (rc && conn->datadgst_en)
769                                 /*
770                                  * data-in is complete, but buffer not...
771                                  */
772                                 partial_sg_digest_update(&tcp_conn->rx_hash,
773                                                          &sg[i],
774                                                          sg[i].offset,
775                                                          sg[i].length-rc);
776                         rc = 0;
777                         break;
778                 }
779
780                 if (!tcp_conn->in.copy)
781                         return -EAGAIN;
782         }
783         BUG_ON(ctask->data_count);
784
785 done:
786         /* check for non-exceptional status */
787         if (tcp_conn->in.hdr->flags & ISCSI_FLAG_DATA_STATUS) {
788                 debug_scsi("done [sc %lx res %d itt 0x%x flags 0x%x]\n",
789                            (long)sc, sc->result, ctask->itt,
790                            tcp_conn->in.hdr->flags);
791                 spin_lock(&conn->session->lock);
792                 __iscsi_complete_pdu(conn, tcp_conn->in.hdr, NULL, 0);
793                 spin_unlock(&conn->session->lock);
794         }
795
796         return rc;
797 }
798
799 static int
800 iscsi_data_recv(struct iscsi_conn *conn)
801 {
802         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
803         int rc = 0, opcode;
804
805         opcode = tcp_conn->in.hdr->opcode & ISCSI_OPCODE_MASK;
806         switch (opcode) {
807         case ISCSI_OP_SCSI_DATA_IN:
808                 rc = iscsi_scsi_data_in(conn);
809                 break;
810         case ISCSI_OP_SCSI_CMD_RSP:
811         case ISCSI_OP_TEXT_RSP:
812         case ISCSI_OP_LOGIN_RSP:
813         case ISCSI_OP_ASYNC_EVENT:
814         case ISCSI_OP_REJECT:
815                 /*
816                  * Collect data segment to the connection's data
817                  * placeholder
818                  */
819                 if (iscsi_tcp_copy(conn, tcp_conn->in.datalen)) {
820                         rc = -EAGAIN;
821                         goto exit;
822                 }
823
824                 rc = iscsi_complete_pdu(conn, tcp_conn->in.hdr, conn->data,
825                                         tcp_conn->in.datalen);
826                 if (!rc && conn->datadgst_en && opcode != ISCSI_OP_LOGIN_RSP)
827                         iscsi_recv_digest_update(tcp_conn, conn->data,
828                                                 tcp_conn->in.datalen);
829                 break;
830         default:
831                 BUG_ON(1);
832         }
833 exit:
834         return rc;
835 }
836
837 /**
838  * iscsi_tcp_data_recv - TCP receive in sendfile fashion
839  * @rd_desc: read descriptor
840  * @skb: socket buffer
841  * @offset: offset in skb
842  * @len: skb->len - offset
843  **/
844 static int
845 iscsi_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
846                 unsigned int offset, size_t len)
847 {
848         int rc;
849         struct iscsi_conn *conn = rd_desc->arg.data;
850         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
851         int processed;
852         char pad[ISCSI_PAD_LEN];
853         struct scatterlist sg;
854
855         /*
856          * Save current SKB and its offset in the corresponding
857          * connection context.
858          */
859         tcp_conn->in.copy = skb->len - offset;
860         tcp_conn->in.offset = offset;
861         tcp_conn->in.skb = skb;
862         tcp_conn->in.len = tcp_conn->in.copy;
863         BUG_ON(tcp_conn->in.copy <= 0);
864         debug_tcp("in %d bytes\n", tcp_conn->in.copy);
865
866 more:
867         tcp_conn->in.copied = 0;
868         rc = 0;
869
870         if (unlikely(conn->suspend_rx)) {
871                 debug_tcp("conn %d Rx suspended!\n", conn->id);
872                 return 0;
873         }
874
875         if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER ||
876             tcp_conn->in_progress == IN_PROGRESS_HEADER_GATHER) {
877                 rc = iscsi_hdr_extract(tcp_conn);
878                 if (rc) {
879                        if (rc == -EAGAIN)
880                                 goto nomore;
881                        else {
882                                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
883                                 return 0;
884                        }
885                 }
886
887                 /*
888                  * Verify and process incoming PDU header.
889                  */
890                 rc = iscsi_tcp_hdr_recv(conn);
891                 if (!rc && tcp_conn->in.datalen) {
892                         if (conn->datadgst_en)
893                                 crypto_hash_init(&tcp_conn->rx_hash);
894                         tcp_conn->in_progress = IN_PROGRESS_DATA_RECV;
895                 } else if (rc) {
896                         iscsi_conn_failure(conn, rc);
897                         return 0;
898                 }
899         }
900
901         if (tcp_conn->in_progress == IN_PROGRESS_DDIGEST_RECV &&
902             tcp_conn->in.copy) {
903                 uint32_t recv_digest;
904
905                 debug_tcp("extra data_recv offset %d copy %d\n",
906                           tcp_conn->in.offset, tcp_conn->in.copy);
907
908                 if (!tcp_conn->data_copied) {
909                         if (tcp_conn->in.padding) {
910                                 debug_tcp("padding -> %d\n",
911                                           tcp_conn->in.padding);
912                                 memset(pad, 0, tcp_conn->in.padding);
913                                 sg_init_one(&sg, pad, tcp_conn->in.padding);
914                                 crypto_hash_update(&tcp_conn->rx_hash,
915                                                    &sg, sg.length);
916                         }
917                         crypto_hash_final(&tcp_conn->rx_hash,
918                                           (u8 *) &tcp_conn->in.datadgst);
919                         debug_tcp("rx digest 0x%x\n", tcp_conn->in.datadgst);
920                 }
921
922                 rc = iscsi_tcp_copy(conn, sizeof(uint32_t));
923                 if (rc) {
924                         if (rc == -EAGAIN)
925                                 goto again;
926                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
927                         return 0;
928                 }
929
930                 memcpy(&recv_digest, conn->data, sizeof(uint32_t));
931                 if (recv_digest != tcp_conn->in.datadgst) {
932                         debug_tcp("iscsi_tcp: data digest error!"
933                                   "0x%x != 0x%x\n", recv_digest,
934                                   tcp_conn->in.datadgst);
935                         iscsi_conn_failure(conn, ISCSI_ERR_DATA_DGST);
936                         return 0;
937                 } else {
938                         debug_tcp("iscsi_tcp: data digest match!"
939                                   "0x%x == 0x%x\n", recv_digest,
940                                   tcp_conn->in.datadgst);
941                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
942                 }
943         }
944
945         if (tcp_conn->in_progress == IN_PROGRESS_DATA_RECV &&
946             tcp_conn->in.copy) {
947                 debug_tcp("data_recv offset %d copy %d\n",
948                        tcp_conn->in.offset, tcp_conn->in.copy);
949
950                 rc = iscsi_data_recv(conn);
951                 if (rc) {
952                         if (rc == -EAGAIN)
953                                 goto again;
954                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
955                         return 0;
956                 }
957
958                 if (tcp_conn->in.padding)
959                         tcp_conn->in_progress = IN_PROGRESS_PAD_RECV;
960                 else if (conn->datadgst_en)
961                         tcp_conn->in_progress = IN_PROGRESS_DDIGEST_RECV;
962                 else
963                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
964                 tcp_conn->data_copied = 0;
965         }
966
967         if (tcp_conn->in_progress == IN_PROGRESS_PAD_RECV &&
968             tcp_conn->in.copy) {
969                 int copylen = min(tcp_conn->in.padding - tcp_conn->data_copied,
970                                   tcp_conn->in.copy);
971
972                 tcp_conn->in.copy -= copylen;
973                 tcp_conn->in.offset += copylen;
974                 tcp_conn->data_copied += copylen;
975
976                 if (tcp_conn->data_copied != tcp_conn->in.padding)
977                         tcp_conn->in_progress = IN_PROGRESS_PAD_RECV;
978                 else if (conn->datadgst_en)
979                         tcp_conn->in_progress = IN_PROGRESS_DDIGEST_RECV;
980                 else
981                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
982                 tcp_conn->data_copied = 0;
983         }
984
985         debug_tcp("f, processed %d from out of %d padding %d\n",
986                tcp_conn->in.offset - offset, (int)len, tcp_conn->in.padding);
987         BUG_ON(tcp_conn->in.offset - offset > len);
988
989         if (tcp_conn->in.offset - offset != len) {
990                 debug_tcp("continue to process %d bytes\n",
991                        (int)len - (tcp_conn->in.offset - offset));
992                 goto more;
993         }
994
995 nomore:
996         processed = tcp_conn->in.offset - offset;
997         BUG_ON(processed == 0);
998         return processed;
999
1000 again:
1001         processed = tcp_conn->in.offset - offset;
1002         debug_tcp("c, processed %d from out of %d rd_desc_cnt %d\n",
1003                   processed, (int)len, (int)rd_desc->count);
1004         BUG_ON(processed == 0);
1005         BUG_ON(processed > len);
1006
1007         conn->rxdata_octets += processed;
1008         return processed;
1009 }
1010
1011 static void
1012 iscsi_tcp_data_ready(struct sock *sk, int flag)
1013 {
1014         struct iscsi_conn *conn = sk->sk_user_data;
1015         read_descriptor_t rd_desc;
1016
1017         read_lock(&sk->sk_callback_lock);
1018
1019         /*
1020          * Use rd_desc to pass 'conn' to iscsi_tcp_data_recv.
1021          * We set count to 1 because we want the network layer to
1022          * hand us all the skbs that are available. iscsi_tcp_data_recv
1023          * handled pdus that cross buffers or pdus that still need data.
1024          */
1025         rd_desc.arg.data = conn;
1026         rd_desc.count = 1;
1027         tcp_read_sock(sk, &rd_desc, iscsi_tcp_data_recv);
1028
1029         read_unlock(&sk->sk_callback_lock);
1030 }
1031
1032 static void
1033 iscsi_tcp_state_change(struct sock *sk)
1034 {
1035         struct iscsi_tcp_conn *tcp_conn;
1036         struct iscsi_conn *conn;
1037         struct iscsi_session *session;
1038         void (*old_state_change)(struct sock *);
1039
1040         read_lock(&sk->sk_callback_lock);
1041
1042         conn = (struct iscsi_conn*)sk->sk_user_data;
1043         session = conn->session;
1044
1045         if ((sk->sk_state == TCP_CLOSE_WAIT ||
1046              sk->sk_state == TCP_CLOSE) &&
1047             !atomic_read(&sk->sk_rmem_alloc)) {
1048                 debug_tcp("iscsi_tcp_state_change: TCP_CLOSE|TCP_CLOSE_WAIT\n");
1049                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1050         }
1051
1052         tcp_conn = conn->dd_data;
1053         old_state_change = tcp_conn->old_state_change;
1054
1055         read_unlock(&sk->sk_callback_lock);
1056
1057         old_state_change(sk);
1058 }
1059
1060 /**
1061  * iscsi_write_space - Called when more output buffer space is available
1062  * @sk: socket space is available for
1063  **/
1064 static void
1065 iscsi_write_space(struct sock *sk)
1066 {
1067         struct iscsi_conn *conn = (struct iscsi_conn*)sk->sk_user_data;
1068         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1069
1070         tcp_conn->old_write_space(sk);
1071         debug_tcp("iscsi_write_space: cid %d\n", conn->id);
1072         scsi_queue_work(conn->session->host, &conn->xmitwork);
1073 }
1074
1075 static void
1076 iscsi_conn_set_callbacks(struct iscsi_conn *conn)
1077 {
1078         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1079         struct sock *sk = tcp_conn->sock->sk;
1080
1081         /* assign new callbacks */
1082         write_lock_bh(&sk->sk_callback_lock);
1083         sk->sk_user_data = conn;
1084         tcp_conn->old_data_ready = sk->sk_data_ready;
1085         tcp_conn->old_state_change = sk->sk_state_change;
1086         tcp_conn->old_write_space = sk->sk_write_space;
1087         sk->sk_data_ready = iscsi_tcp_data_ready;
1088         sk->sk_state_change = iscsi_tcp_state_change;
1089         sk->sk_write_space = iscsi_write_space;
1090         write_unlock_bh(&sk->sk_callback_lock);
1091 }
1092
1093 static void
1094 iscsi_conn_restore_callbacks(struct iscsi_tcp_conn *tcp_conn)
1095 {
1096         struct sock *sk = tcp_conn->sock->sk;
1097
1098         /* restore socket callbacks, see also: iscsi_conn_set_callbacks() */
1099         write_lock_bh(&sk->sk_callback_lock);
1100         sk->sk_user_data    = NULL;
1101         sk->sk_data_ready   = tcp_conn->old_data_ready;
1102         sk->sk_state_change = tcp_conn->old_state_change;
1103         sk->sk_write_space  = tcp_conn->old_write_space;
1104         sk->sk_no_check  = 0;
1105         write_unlock_bh(&sk->sk_callback_lock);
1106 }
1107
1108 /**
1109  * iscsi_send - generic send routine
1110  * @sk: kernel's socket
1111  * @buf: buffer to write from
1112  * @size: actual size to write
1113  * @flags: socket's flags
1114  */
1115 static inline int
1116 iscsi_send(struct iscsi_conn *conn, struct iscsi_buf *buf, int size, int flags)
1117 {
1118         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1119         struct socket *sk = tcp_conn->sock;
1120         int offset = buf->sg.offset + buf->sent, res;
1121
1122         /*
1123          * if we got use_sg=0 or are sending something we kmallocd
1124          * then we did not have to do kmap (kmap returns page_address)
1125          *
1126          * if we got use_sg > 0, but had to drop down, we do not
1127          * set clustering so this should only happen for that
1128          * slab case.
1129          */
1130         if (buf->use_sendmsg)
1131                 res = sock_no_sendpage(sk, buf->sg.page, offset, size, flags);
1132         else
1133                 res = tcp_conn->sendpage(sk, buf->sg.page, offset, size, flags);
1134
1135         if (res >= 0) {
1136                 conn->txdata_octets += res;
1137                 buf->sent += res;
1138                 return res;
1139         }
1140
1141         tcp_conn->sendpage_failures_cnt++;
1142         if (res == -EAGAIN)
1143                 res = -ENOBUFS;
1144         else
1145                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1146         return res;
1147 }
1148
1149 /**
1150  * iscsi_sendhdr - send PDU Header via tcp_sendpage()
1151  * @conn: iscsi connection
1152  * @buf: buffer to write from
1153  * @datalen: lenght of data to be sent after the header
1154  *
1155  * Notes:
1156  *      (Tx, Fast Path)
1157  **/
1158 static inline int
1159 iscsi_sendhdr(struct iscsi_conn *conn, struct iscsi_buf *buf, int datalen)
1160 {
1161         int flags = 0; /* MSG_DONTWAIT; */
1162         int res, size;
1163
1164         size = buf->sg.length - buf->sent;
1165         BUG_ON(buf->sent + size > buf->sg.length);
1166         if (buf->sent + size != buf->sg.length || datalen)
1167                 flags |= MSG_MORE;
1168
1169         res = iscsi_send(conn, buf, size, flags);
1170         debug_tcp("sendhdr %d bytes, sent %d res %d\n", size, buf->sent, res);
1171         if (res >= 0) {
1172                 if (size != res)
1173                         return -EAGAIN;
1174                 return 0;
1175         }
1176
1177         return res;
1178 }
1179
1180 /**
1181  * iscsi_sendpage - send one page of iSCSI Data-Out.
1182  * @conn: iscsi connection
1183  * @buf: buffer to write from
1184  * @count: remaining data
1185  * @sent: number of bytes sent
1186  *
1187  * Notes:
1188  *      (Tx, Fast Path)
1189  **/
1190 static inline int
1191 iscsi_sendpage(struct iscsi_conn *conn, struct iscsi_buf *buf,
1192                int *count, int *sent)
1193 {
1194         int flags = 0; /* MSG_DONTWAIT; */
1195         int res, size;
1196
1197         size = buf->sg.length - buf->sent;
1198         BUG_ON(buf->sent + size > buf->sg.length);
1199         if (size > *count)
1200                 size = *count;
1201         if (buf->sent + size != buf->sg.length || *count != size)
1202                 flags |= MSG_MORE;
1203
1204         res = iscsi_send(conn, buf, size, flags);
1205         debug_tcp("sendpage: %d bytes, sent %d left %d sent %d res %d\n",
1206                   size, buf->sent, *count, *sent, res);
1207         if (res >= 0) {
1208                 *count -= res;
1209                 *sent += res;
1210                 if (size != res)
1211                         return -EAGAIN;
1212                 return 0;
1213         }
1214
1215         return res;
1216 }
1217
1218 static inline void
1219 iscsi_data_digest_init(struct iscsi_tcp_conn *tcp_conn,
1220                       struct iscsi_tcp_cmd_task *tcp_ctask)
1221 {
1222         crypto_hash_init(&tcp_conn->tx_hash);
1223         tcp_ctask->digest_count = 4;
1224 }
1225
1226 /**
1227  * iscsi_solicit_data_cont - initialize next Data-Out
1228  * @conn: iscsi connection
1229  * @ctask: scsi command task
1230  * @r2t: R2T info
1231  * @left: bytes left to transfer
1232  *
1233  * Notes:
1234  *      Initialize next Data-Out within this R2T sequence and continue
1235  *      to process next Scatter-Gather element(if any) of this SCSI command.
1236  *
1237  *      Called under connection lock.
1238  **/
1239 static void
1240 iscsi_solicit_data_cont(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1241                         struct iscsi_r2t_info *r2t, int left)
1242 {
1243         struct iscsi_data *hdr;
1244         struct scsi_cmnd *sc = ctask->sc;
1245         int new_offset;
1246
1247         hdr = &r2t->dtask.hdr;
1248         memset(hdr, 0, sizeof(struct iscsi_data));
1249         hdr->ttt = r2t->ttt;
1250         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
1251         r2t->solicit_datasn++;
1252         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
1253         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1254         hdr->itt = ctask->hdr->itt;
1255         hdr->exp_statsn = r2t->exp_statsn;
1256         new_offset = r2t->data_offset + r2t->sent;
1257         hdr->offset = cpu_to_be32(new_offset);
1258         if (left > conn->max_xmit_dlength) {
1259                 hton24(hdr->dlength, conn->max_xmit_dlength);
1260                 r2t->data_count = conn->max_xmit_dlength;
1261         } else {
1262                 hton24(hdr->dlength, left);
1263                 r2t->data_count = left;
1264                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
1265         }
1266         conn->dataout_pdus_cnt++;
1267
1268         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
1269                            sizeof(struct iscsi_hdr));
1270
1271         if (iscsi_buf_left(&r2t->sendbuf))
1272                 return;
1273
1274         if (sc->use_sg) {
1275                 iscsi_buf_init_sg(&r2t->sendbuf, r2t->sg);
1276                 r2t->sg += 1;
1277         } else {
1278                 iscsi_buf_init_iov(&r2t->sendbuf,
1279                             (char*)sc->request_buffer + new_offset,
1280                             r2t->data_count);
1281                 r2t->sg = NULL;
1282         }
1283 }
1284
1285 static void iscsi_set_padding(struct iscsi_tcp_cmd_task *tcp_ctask,
1286                               unsigned long len)
1287 {
1288         tcp_ctask->pad_count = len & (ISCSI_PAD_LEN - 1);
1289         if (!tcp_ctask->pad_count)
1290                 return;
1291
1292         tcp_ctask->pad_count = ISCSI_PAD_LEN - tcp_ctask->pad_count;
1293         debug_scsi("write padding %d bytes\n", tcp_ctask->pad_count);
1294         tcp_ctask->xmstate |= XMSTATE_W_PAD;
1295 }
1296
1297 /**
1298  * iscsi_tcp_cmd_init - Initialize iSCSI SCSI_READ or SCSI_WRITE commands
1299  * @conn: iscsi connection
1300  * @ctask: scsi command task
1301  * @sc: scsi command
1302  **/
1303 static void
1304 iscsi_tcp_cmd_init(struct iscsi_cmd_task *ctask)
1305 {
1306         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1307
1308         BUG_ON(__kfifo_len(tcp_ctask->r2tqueue));
1309         tcp_ctask->xmstate = XMSTATE_CMD_HDR_INIT;
1310 }
1311
1312 /**
1313  * iscsi_tcp_mtask_xmit - xmit management(immediate) task
1314  * @conn: iscsi connection
1315  * @mtask: task management task
1316  *
1317  * Notes:
1318  *      The function can return -EAGAIN in which case caller must
1319  *      call it again later, or recover. '0' return code means successful
1320  *      xmit.
1321  *
1322  *      Management xmit state machine consists of these states:
1323  *              XMSTATE_IMM_HDR_INIT    - calculate digest of PDU Header
1324  *              XMSTATE_IMM_HDR         - PDU Header xmit in progress
1325  *              XMSTATE_IMM_DATA        - PDU Data xmit in progress
1326  *              XMSTATE_IDLE            - management PDU is done
1327  **/
1328 static int
1329 iscsi_tcp_mtask_xmit(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask)
1330 {
1331         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1332         int rc;
1333
1334         debug_scsi("mtask deq [cid %d state %x itt 0x%x]\n",
1335                 conn->id, tcp_mtask->xmstate, mtask->itt);
1336
1337         if (tcp_mtask->xmstate & XMSTATE_IMM_HDR_INIT) {
1338                 iscsi_buf_init_iov(&tcp_mtask->headbuf, (char*)mtask->hdr,
1339                                    sizeof(struct iscsi_hdr));
1340
1341                 if (mtask->data_count) {
1342                         tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1343                         iscsi_buf_init_iov(&tcp_mtask->sendbuf,
1344                                            (char*)mtask->data,
1345                                            mtask->data_count);
1346                 }
1347
1348                 if (conn->c_stage != ISCSI_CONN_INITIAL_STAGE &&
1349                     conn->stop_stage != STOP_CONN_RECOVER &&
1350                     conn->hdrdgst_en)
1351                         iscsi_hdr_digest(conn, &tcp_mtask->headbuf,
1352                                         (u8*)tcp_mtask->hdrext);
1353
1354                 tcp_mtask->sent = 0;
1355                 tcp_mtask->xmstate &= ~XMSTATE_IMM_HDR_INIT;
1356                 tcp_mtask->xmstate |= XMSTATE_IMM_HDR;
1357         }
1358
1359         if (tcp_mtask->xmstate & XMSTATE_IMM_HDR) {
1360                 rc = iscsi_sendhdr(conn, &tcp_mtask->headbuf,
1361                                    mtask->data_count);
1362                 if (rc)
1363                         return rc;
1364                 tcp_mtask->xmstate &= ~XMSTATE_IMM_HDR;
1365         }
1366
1367         if (tcp_mtask->xmstate & XMSTATE_IMM_DATA) {
1368                 BUG_ON(!mtask->data_count);
1369                 tcp_mtask->xmstate &= ~XMSTATE_IMM_DATA;
1370                 /* FIXME: implement.
1371                  * Virtual buffer could be spreaded across multiple pages...
1372                  */
1373                 do {
1374                         int rc;
1375
1376                         rc = iscsi_sendpage(conn, &tcp_mtask->sendbuf,
1377                                         &mtask->data_count, &tcp_mtask->sent);
1378                         if (rc) {
1379                                 tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1380                                 return rc;
1381                         }
1382                 } while (mtask->data_count);
1383         }
1384
1385         BUG_ON(tcp_mtask->xmstate != XMSTATE_IDLE);
1386         if (mtask->hdr->itt == RESERVED_ITT) {
1387                 struct iscsi_session *session = conn->session;
1388
1389                 spin_lock_bh(&session->lock);
1390                 list_del(&conn->mtask->running);
1391                 __kfifo_put(session->mgmtpool.queue, (void*)&conn->mtask,
1392                             sizeof(void*));
1393                 spin_unlock_bh(&session->lock);
1394         }
1395         return 0;
1396 }
1397
1398 static int
1399 iscsi_send_cmd_hdr(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1400 {
1401         struct scsi_cmnd *sc = ctask->sc;
1402         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1403         int rc = 0;
1404
1405         if (tcp_ctask->xmstate & XMSTATE_CMD_HDR_INIT) {
1406                 tcp_ctask->sent = 0;
1407                 tcp_ctask->sg_count = 0;
1408                 tcp_ctask->exp_datasn = 0;
1409
1410                 if (sc->sc_data_direction == DMA_TO_DEVICE) {
1411                         if (sc->use_sg) {
1412                                 struct scatterlist *sg = sc->request_buffer;
1413
1414                                 iscsi_buf_init_sg(&tcp_ctask->sendbuf, sg);
1415                                 tcp_ctask->sg = sg + 1;
1416                                 tcp_ctask->bad_sg = sg + sc->use_sg;
1417                         } else {
1418                                 iscsi_buf_init_iov(&tcp_ctask->sendbuf,
1419                                                    sc->request_buffer,
1420                                                    sc->request_bufflen);
1421                                 tcp_ctask->sg = NULL;
1422                                 tcp_ctask->bad_sg = NULL;
1423                         }
1424
1425                         debug_scsi("cmd [itt 0x%x total %d imm_data %d "
1426                                    "unsol count %d, unsol offset %d]\n",
1427                                    ctask->itt, sc->request_bufflen,
1428                                    ctask->imm_count, ctask->unsol_count,
1429                                    ctask->unsol_offset);
1430                 }
1431
1432                 iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)ctask->hdr,
1433                                   sizeof(struct iscsi_hdr));
1434
1435                 if (conn->hdrdgst_en)
1436                         iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1437                                          (u8*)tcp_ctask->hdrext);
1438                 tcp_ctask->xmstate &= ~XMSTATE_CMD_HDR_INIT;
1439                 tcp_ctask->xmstate |= XMSTATE_CMD_HDR_XMIT;
1440         }
1441
1442         if (tcp_ctask->xmstate & XMSTATE_CMD_HDR_XMIT) {
1443                 rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->imm_count);
1444                 if (rc)
1445                         return rc;
1446                 tcp_ctask->xmstate &= ~XMSTATE_CMD_HDR_XMIT;
1447
1448                 if (sc->sc_data_direction != DMA_TO_DEVICE)
1449                         return 0;
1450
1451                 if (ctask->imm_count) {
1452                         tcp_ctask->xmstate |= XMSTATE_IMM_DATA;
1453                         iscsi_set_padding(tcp_ctask, ctask->imm_count);
1454
1455                         if (ctask->conn->datadgst_en) {
1456                                 iscsi_data_digest_init(ctask->conn->dd_data,
1457                                                        tcp_ctask);
1458                                 tcp_ctask->immdigest = 0;
1459                         }
1460                 }
1461
1462                 if (ctask->unsol_count)
1463                         tcp_ctask->xmstate |=
1464                                         XMSTATE_UNS_HDR | XMSTATE_UNS_INIT;
1465         }
1466         return rc;
1467 }
1468
1469 static int
1470 iscsi_send_padding(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1471 {
1472         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1473         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1474         int sent = 0, rc;
1475
1476         if (tcp_ctask->xmstate & XMSTATE_W_PAD) {
1477                 iscsi_buf_init_iov(&tcp_ctask->sendbuf, (char*)&tcp_ctask->pad,
1478                                    tcp_ctask->pad_count);
1479                 if (conn->datadgst_en)
1480                         crypto_hash_update(&tcp_conn->tx_hash,
1481                                            &tcp_ctask->sendbuf.sg,
1482                                            tcp_ctask->sendbuf.sg.length);
1483         } else if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_PAD))
1484                 return 0;
1485
1486         tcp_ctask->xmstate &= ~XMSTATE_W_PAD;
1487         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_PAD;
1488         debug_scsi("sending %d pad bytes for itt 0x%x\n",
1489                    tcp_ctask->pad_count, ctask->itt);
1490         rc = iscsi_sendpage(conn, &tcp_ctask->sendbuf, &tcp_ctask->pad_count,
1491                            &sent);
1492         if (rc) {
1493                 debug_scsi("padding send failed %d\n", rc);
1494                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_PAD;
1495         }
1496         return rc;
1497 }
1498
1499 static int
1500 iscsi_send_digest(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1501                         struct iscsi_buf *buf, uint32_t *digest)
1502 {
1503         struct iscsi_tcp_cmd_task *tcp_ctask;
1504         struct iscsi_tcp_conn *tcp_conn;
1505         int rc, sent = 0;
1506
1507         if (!conn->datadgst_en)
1508                 return 0;
1509
1510         tcp_ctask = ctask->dd_data;
1511         tcp_conn = conn->dd_data;
1512
1513         if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_DATA_DIGEST)) {
1514                 crypto_hash_final(&tcp_conn->tx_hash, (u8*)digest);
1515                 iscsi_buf_init_iov(buf, (char*)digest, 4);
1516         }
1517         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_DATA_DIGEST;
1518
1519         rc = iscsi_sendpage(conn, buf, &tcp_ctask->digest_count, &sent);
1520         if (!rc)
1521                 debug_scsi("sent digest 0x%x for itt 0x%x\n", *digest,
1522                           ctask->itt);
1523         else {
1524                 debug_scsi("sending digest 0x%x failed for itt 0x%x!\n",
1525                           *digest, ctask->itt);
1526                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_DATA_DIGEST;
1527         }
1528         return rc;
1529 }
1530
1531 static int
1532 iscsi_send_data(struct iscsi_cmd_task *ctask, struct iscsi_buf *sendbuf,
1533                 struct scatterlist **sg, int *sent, int *count,
1534                 struct iscsi_buf *digestbuf, uint32_t *digest)
1535 {
1536         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1537         struct iscsi_conn *conn = ctask->conn;
1538         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1539         int rc, buf_sent, offset;
1540
1541         while (*count) {
1542                 buf_sent = 0;
1543                 offset = sendbuf->sent;
1544
1545                 rc = iscsi_sendpage(conn, sendbuf, count, &buf_sent);
1546                 *sent = *sent + buf_sent;
1547                 if (buf_sent && conn->datadgst_en)
1548                         partial_sg_digest_update(&tcp_conn->tx_hash,
1549                                 &sendbuf->sg, sendbuf->sg.offset + offset,
1550                                 buf_sent);
1551                 if (!iscsi_buf_left(sendbuf) && *sg != tcp_ctask->bad_sg) {
1552                         iscsi_buf_init_sg(sendbuf, *sg);
1553                         *sg = *sg + 1;
1554                 }
1555
1556                 if (rc)
1557                         return rc;
1558         }
1559
1560         rc = iscsi_send_padding(conn, ctask);
1561         if (rc)
1562                 return rc;
1563
1564         return iscsi_send_digest(conn, ctask, digestbuf, digest);
1565 }
1566
1567 static int
1568 iscsi_send_unsol_hdr(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1569 {
1570         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1571         struct iscsi_data_task *dtask;
1572         int rc;
1573
1574         tcp_ctask->xmstate |= XMSTATE_UNS_DATA;
1575         if (tcp_ctask->xmstate & XMSTATE_UNS_INIT) {
1576                 dtask = &tcp_ctask->unsol_dtask;
1577
1578                 iscsi_prep_unsolicit_data_pdu(ctask, &dtask->hdr);
1579                 iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)&dtask->hdr,
1580                                    sizeof(struct iscsi_hdr));
1581                 if (conn->hdrdgst_en)
1582                         iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1583                                         (u8*)dtask->hdrext);
1584
1585                 tcp_ctask->xmstate &= ~XMSTATE_UNS_INIT;
1586                 iscsi_set_padding(tcp_ctask, ctask->data_count);
1587         }
1588
1589         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->data_count);
1590         if (rc) {
1591                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1592                 tcp_ctask->xmstate |= XMSTATE_UNS_HDR;
1593                 return rc;
1594         }
1595
1596         if (conn->datadgst_en) {
1597                 dtask = &tcp_ctask->unsol_dtask;
1598                 iscsi_data_digest_init(ctask->conn->dd_data, tcp_ctask);
1599                 dtask->digest = 0;
1600         }
1601
1602         debug_scsi("uns dout [itt 0x%x dlen %d sent %d]\n",
1603                    ctask->itt, ctask->unsol_count, tcp_ctask->sent);
1604         return 0;
1605 }
1606
1607 static int
1608 iscsi_send_unsol_pdu(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1609 {
1610         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1611         int rc;
1612
1613         if (tcp_ctask->xmstate & XMSTATE_UNS_HDR) {
1614                 BUG_ON(!ctask->unsol_count);
1615                 tcp_ctask->xmstate &= ~XMSTATE_UNS_HDR;
1616 send_hdr:
1617                 rc = iscsi_send_unsol_hdr(conn, ctask);
1618                 if (rc)
1619                         return rc;
1620         }
1621
1622         if (tcp_ctask->xmstate & XMSTATE_UNS_DATA) {
1623                 struct iscsi_data_task *dtask = &tcp_ctask->unsol_dtask;
1624                 int start = tcp_ctask->sent;
1625
1626                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1627                                      &tcp_ctask->sent, &ctask->data_count,
1628                                      &dtask->digestbuf, &dtask->digest);
1629                 ctask->unsol_count -= tcp_ctask->sent - start;
1630                 if (rc)
1631                         return rc;
1632                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1633                 /*
1634                  * Done with the Data-Out. Next, check if we need
1635                  * to send another unsolicited Data-Out.
1636                  */
1637                 if (ctask->unsol_count) {
1638                         debug_scsi("sending more uns\n");
1639                         tcp_ctask->xmstate |= XMSTATE_UNS_INIT;
1640                         goto send_hdr;
1641                 }
1642         }
1643         return 0;
1644 }
1645
1646 static int iscsi_send_sol_pdu(struct iscsi_conn *conn,
1647                               struct iscsi_cmd_task *ctask)
1648 {
1649         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1650         struct iscsi_session *session = conn->session;
1651         struct iscsi_r2t_info *r2t;
1652         struct iscsi_data_task *dtask;
1653         int left, rc;
1654
1655         if (tcp_ctask->xmstate & XMSTATE_SOL_HDR_INIT) {
1656                 if (!tcp_ctask->r2t) {
1657                         spin_lock_bh(&session->lock);
1658                         __kfifo_get(tcp_ctask->r2tqueue, (void*)&tcp_ctask->r2t,
1659                                     sizeof(void*));
1660                         spin_unlock_bh(&session->lock);
1661                 }
1662 send_hdr:
1663                 r2t = tcp_ctask->r2t;
1664                 dtask = &r2t->dtask;
1665
1666                 if (conn->hdrdgst_en)
1667                         iscsi_hdr_digest(conn, &r2t->headbuf,
1668                                         (u8*)dtask->hdrext);
1669                 tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR_INIT;
1670                 tcp_ctask->xmstate |= XMSTATE_SOL_HDR;
1671         }
1672
1673         if (tcp_ctask->xmstate & XMSTATE_SOL_HDR) {
1674                 r2t = tcp_ctask->r2t;
1675                 dtask = &r2t->dtask;
1676
1677                 rc = iscsi_sendhdr(conn, &r2t->headbuf, r2t->data_count);
1678                 if (rc)
1679                         return rc;
1680                 tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1681                 tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1682
1683                 if (conn->datadgst_en) {
1684                         iscsi_data_digest_init(conn->dd_data, tcp_ctask);
1685                         dtask->digest = 0;
1686                 }
1687
1688                 iscsi_set_padding(tcp_ctask, r2t->data_count);
1689                 debug_scsi("sol dout [dsn %d itt 0x%x dlen %d sent %d]\n",
1690                         r2t->solicit_datasn - 1, ctask->itt, r2t->data_count,
1691                         r2t->sent);
1692         }
1693
1694         if (tcp_ctask->xmstate & XMSTATE_SOL_DATA) {
1695                 r2t = tcp_ctask->r2t;
1696                 dtask = &r2t->dtask;
1697
1698                 rc = iscsi_send_data(ctask, &r2t->sendbuf, &r2t->sg,
1699                                      &r2t->sent, &r2t->data_count,
1700                                      &dtask->digestbuf, &dtask->digest);
1701                 if (rc)
1702                         return rc;
1703                 tcp_ctask->xmstate &= ~XMSTATE_SOL_DATA;
1704
1705                 /*
1706                  * Done with this Data-Out. Next, check if we have
1707                  * to send another Data-Out for this R2T.
1708                  */
1709                 BUG_ON(r2t->data_length - r2t->sent < 0);
1710                 left = r2t->data_length - r2t->sent;
1711                 if (left) {
1712                         iscsi_solicit_data_cont(conn, ctask, r2t, left);
1713                         goto send_hdr;
1714                 }
1715
1716                 /*
1717                  * Done with this R2T. Check if there are more
1718                  * outstanding R2Ts ready to be processed.
1719                  */
1720                 spin_lock_bh(&session->lock);
1721                 tcp_ctask->r2t = NULL;
1722                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
1723                             sizeof(void*));
1724                 if (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t,
1725                                 sizeof(void*))) {
1726                         tcp_ctask->r2t = r2t;
1727                         spin_unlock_bh(&session->lock);
1728                         goto send_hdr;
1729                 }
1730                 spin_unlock_bh(&session->lock);
1731         }
1732         return 0;
1733 }
1734
1735 /**
1736  * iscsi_tcp_ctask_xmit - xmit normal PDU task
1737  * @conn: iscsi connection
1738  * @ctask: iscsi command task
1739  *
1740  * Notes:
1741  *      The function can return -EAGAIN in which case caller must
1742  *      call it again later, or recover. '0' return code means successful
1743  *      xmit.
1744  *      The function is devided to logical helpers (above) for the different
1745  *      xmit stages.
1746  *
1747  *iscsi_send_cmd_hdr()
1748  *      XMSTATE_CMD_HDR_INIT - prepare Header and Data buffers Calculate
1749  *                             Header Digest
1750  *      XMSTATE_CMD_HDR_XMIT - Transmit header in progress
1751  *
1752  *iscsi_send_padding
1753  *      XMSTATE_W_PAD        - Prepare and send pading
1754  *      XMSTATE_W_RESEND_PAD - retry send pading
1755  *
1756  *iscsi_send_digest
1757  *      XMSTATE_W_RESEND_DATA_DIGEST - Finalize and send Data Digest
1758  *      XMSTATE_W_RESEND_DATA_DIGEST - retry sending digest
1759  *
1760  *iscsi_send_unsol_hdr
1761  *      XMSTATE_UNS_INIT     - prepare un-solicit data header and digest
1762  *      XMSTATE_UNS_HDR      - send un-solicit header
1763  *
1764  *iscsi_send_unsol_pdu
1765  *      XMSTATE_UNS_DATA     - send un-solicit data in progress
1766  *
1767  *iscsi_send_sol_pdu
1768  *      XMSTATE_SOL_HDR_INIT - solicit data header and digest initialize
1769  *      XMSTATE_SOL_HDR      - send solicit header
1770  *      XMSTATE_SOL_DATA     - send solicit data
1771  *
1772  *iscsi_tcp_ctask_xmit
1773  *      XMSTATE_IMM_DATA     - xmit managment data (??)
1774  **/
1775 static int
1776 iscsi_tcp_ctask_xmit(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1777 {
1778         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1779         int rc = 0;
1780
1781         debug_scsi("ctask deq [cid %d xmstate %x itt 0x%x]\n",
1782                 conn->id, tcp_ctask->xmstate, ctask->itt);
1783
1784         rc = iscsi_send_cmd_hdr(conn, ctask);
1785         if (rc)
1786                 return rc;
1787         if (ctask->sc->sc_data_direction != DMA_TO_DEVICE)
1788                 return 0;
1789
1790         if (tcp_ctask->xmstate & XMSTATE_IMM_DATA) {
1791                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1792                                      &tcp_ctask->sent, &ctask->imm_count,
1793                                      &tcp_ctask->immbuf, &tcp_ctask->immdigest);
1794                 if (rc)
1795                         return rc;
1796                 tcp_ctask->xmstate &= ~XMSTATE_IMM_DATA;
1797         }
1798
1799         rc = iscsi_send_unsol_pdu(conn, ctask);
1800         if (rc)
1801                 return rc;
1802
1803         rc = iscsi_send_sol_pdu(conn, ctask);
1804         if (rc)
1805                 return rc;
1806
1807         return rc;
1808 }
1809
1810 static struct iscsi_cls_conn *
1811 iscsi_tcp_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1812 {
1813         struct iscsi_conn *conn;
1814         struct iscsi_cls_conn *cls_conn;
1815         struct iscsi_tcp_conn *tcp_conn;
1816
1817         cls_conn = iscsi_conn_setup(cls_session, conn_idx);
1818         if (!cls_conn)
1819                 return NULL;
1820         conn = cls_conn->dd_data;
1821         /*
1822          * due to strange issues with iser these are not set
1823          * in iscsi_conn_setup
1824          */
1825         conn->max_recv_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN;
1826
1827         tcp_conn = kzalloc(sizeof(*tcp_conn), GFP_KERNEL);
1828         if (!tcp_conn)
1829                 goto tcp_conn_alloc_fail;
1830
1831         conn->dd_data = tcp_conn;
1832         tcp_conn->iscsi_conn = conn;
1833         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1834         /* initial operational parameters */
1835         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1836
1837         tcp_conn->tx_hash.tfm = crypto_alloc_hash("crc32c", 0,
1838                                                   CRYPTO_ALG_ASYNC);
1839         tcp_conn->tx_hash.flags = 0;
1840         if (IS_ERR(tcp_conn->tx_hash.tfm)) {
1841                 printk(KERN_ERR "Could not create connection due to crc32c "
1842                        "loading error %ld. Make sure the crc32c module is "
1843                        "built as a module or into the kernel\n",
1844                         PTR_ERR(tcp_conn->tx_hash.tfm));
1845                 goto free_tcp_conn;
1846         }
1847
1848         tcp_conn->rx_hash.tfm = crypto_alloc_hash("crc32c", 0,
1849                                                   CRYPTO_ALG_ASYNC);
1850         tcp_conn->rx_hash.flags = 0;
1851         if (IS_ERR(tcp_conn->rx_hash.tfm)) {
1852                 printk(KERN_ERR "Could not create connection due to crc32c "
1853                        "loading error %ld. Make sure the crc32c module is "
1854                        "built as a module or into the kernel\n",
1855                         PTR_ERR(tcp_conn->rx_hash.tfm));
1856                 goto free_tx_tfm;
1857         }
1858
1859         return cls_conn;
1860
1861 free_tx_tfm:
1862         crypto_free_hash(tcp_conn->tx_hash.tfm);
1863 free_tcp_conn:
1864         kfree(tcp_conn);
1865 tcp_conn_alloc_fail:
1866         iscsi_conn_teardown(cls_conn);
1867         return NULL;
1868 }
1869
1870 static void
1871 iscsi_tcp_release_conn(struct iscsi_conn *conn)
1872 {
1873         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1874
1875         if (!tcp_conn->sock)
1876                 return;
1877
1878         sock_hold(tcp_conn->sock->sk);
1879         iscsi_conn_restore_callbacks(tcp_conn);
1880         sock_put(tcp_conn->sock->sk);
1881
1882         sockfd_put(tcp_conn->sock);
1883         tcp_conn->sock = NULL;
1884         conn->recv_lock = NULL;
1885 }
1886
1887 static void
1888 iscsi_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn)
1889 {
1890         struct iscsi_conn *conn = cls_conn->dd_data;
1891         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1892
1893         iscsi_tcp_release_conn(conn);
1894         iscsi_conn_teardown(cls_conn);
1895
1896         if (tcp_conn->tx_hash.tfm)
1897                 crypto_free_hash(tcp_conn->tx_hash.tfm);
1898         if (tcp_conn->rx_hash.tfm)
1899                 crypto_free_hash(tcp_conn->rx_hash.tfm);
1900
1901         kfree(tcp_conn);
1902 }
1903
1904 static void
1905 iscsi_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1906 {
1907         struct iscsi_conn *conn = cls_conn->dd_data;
1908         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1909
1910         iscsi_conn_stop(cls_conn, flag);
1911         iscsi_tcp_release_conn(conn);
1912         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1913 }
1914
1915 static int
1916 iscsi_tcp_conn_bind(struct iscsi_cls_session *cls_session,
1917                     struct iscsi_cls_conn *cls_conn, uint64_t transport_eph,
1918                     int is_leading)
1919 {
1920         struct iscsi_conn *conn = cls_conn->dd_data;
1921         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1922         struct sock *sk;
1923         struct socket *sock;
1924         int err;
1925
1926         /* lookup for existing socket */
1927         sock = sockfd_lookup((int)transport_eph, &err);
1928         if (!sock) {
1929                 printk(KERN_ERR "iscsi_tcp: sockfd_lookup failed %d\n", err);
1930                 return -EEXIST;
1931         }
1932
1933         err = iscsi_conn_bind(cls_session, cls_conn, is_leading);
1934         if (err)
1935                 return err;
1936
1937         /* bind iSCSI connection and socket */
1938         tcp_conn->sock = sock;
1939
1940         /* setup Socket parameters */
1941         sk = sock->sk;
1942         sk->sk_reuse = 1;
1943         sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */
1944         sk->sk_allocation = GFP_ATOMIC;
1945
1946         /* FIXME: disable Nagle's algorithm */
1947
1948         /*
1949          * Intercept TCP callbacks for sendfile like receive
1950          * processing.
1951          */
1952         conn->recv_lock = &sk->sk_callback_lock;
1953         iscsi_conn_set_callbacks(conn);
1954         tcp_conn->sendpage = tcp_conn->sock->ops->sendpage;
1955         /*
1956          * set receive state machine into initial state
1957          */
1958         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1959
1960         return 0;
1961 }
1962
1963 /* called with host lock */
1964 static void
1965 iscsi_tcp_mgmt_init(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask)
1966 {
1967         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1968         tcp_mtask->xmstate = XMSTATE_IMM_HDR_INIT;
1969 }
1970
1971 static int
1972 iscsi_r2tpool_alloc(struct iscsi_session *session)
1973 {
1974         int i;
1975         int cmd_i;
1976
1977         /*
1978          * initialize per-task: R2T pool and xmit queue
1979          */
1980         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1981                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1982                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1983
1984                 /*
1985                  * pre-allocated x4 as much r2ts to handle race when
1986                  * target acks DataOut faster than we data_xmit() queues
1987                  * could replenish r2tqueue.
1988                  */
1989
1990                 /* R2T pool */
1991                 if (iscsi_pool_init(&tcp_ctask->r2tpool, session->max_r2t * 4,
1992                                     (void***)&tcp_ctask->r2ts,
1993                                     sizeof(struct iscsi_r2t_info))) {
1994                         goto r2t_alloc_fail;
1995                 }
1996
1997                 /* R2T xmit queue */
1998                 tcp_ctask->r2tqueue = kfifo_alloc(
1999                       session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL);
2000                 if (tcp_ctask->r2tqueue == ERR_PTR(-ENOMEM)) {
2001                         iscsi_pool_free(&tcp_ctask->r2tpool,
2002                                         (void**)tcp_ctask->r2ts);
2003                         goto r2t_alloc_fail;
2004                 }
2005         }
2006
2007         return 0;
2008
2009 r2t_alloc_fail:
2010         for (i = 0; i < cmd_i; i++) {
2011                 struct iscsi_cmd_task *ctask = session->cmds[i];
2012                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2013
2014                 kfifo_free(tcp_ctask->r2tqueue);
2015                 iscsi_pool_free(&tcp_ctask->r2tpool,
2016                                 (void**)tcp_ctask->r2ts);
2017         }
2018         return -ENOMEM;
2019 }
2020
2021 static void
2022 iscsi_r2tpool_free(struct iscsi_session *session)
2023 {
2024         int i;
2025
2026         for (i = 0; i < session->cmds_max; i++) {
2027                 struct iscsi_cmd_task *ctask = session->cmds[i];
2028                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2029
2030                 kfifo_free(tcp_ctask->r2tqueue);
2031                 iscsi_pool_free(&tcp_ctask->r2tpool,
2032                                 (void**)tcp_ctask->r2ts);
2033         }
2034 }
2035
2036 static int
2037 iscsi_conn_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param,
2038                      char *buf, int buflen)
2039 {
2040         struct iscsi_conn *conn = cls_conn->dd_data;
2041         struct iscsi_session *session = conn->session;
2042         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2043         int value;
2044
2045         switch(param) {
2046         case ISCSI_PARAM_HDRDGST_EN:
2047                 iscsi_set_param(cls_conn, param, buf, buflen);
2048                 tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
2049                 if (conn->hdrdgst_en)
2050                         tcp_conn->hdr_size += sizeof(__u32);
2051                 break;
2052         case ISCSI_PARAM_DATADGST_EN:
2053                 iscsi_set_param(cls_conn, param, buf, buflen);
2054                 tcp_conn->sendpage = conn->datadgst_en ?
2055                         sock_no_sendpage : tcp_conn->sock->ops->sendpage;
2056                 break;
2057         case ISCSI_PARAM_MAX_R2T:
2058                 sscanf(buf, "%d", &value);
2059                 if (session->max_r2t == roundup_pow_of_two(value))
2060                         break;
2061                 iscsi_r2tpool_free(session);
2062                 iscsi_set_param(cls_conn, param, buf, buflen);
2063                 if (session->max_r2t & (session->max_r2t - 1))
2064                         session->max_r2t = roundup_pow_of_two(session->max_r2t);
2065                 if (iscsi_r2tpool_alloc(session))
2066                         return -ENOMEM;
2067                 break;
2068         default:
2069                 return iscsi_set_param(cls_conn, param, buf, buflen);
2070         }
2071
2072         return 0;
2073 }
2074
2075 static int
2076 iscsi_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn,
2077                          enum iscsi_param param, char *buf)
2078 {
2079         struct iscsi_conn *conn = cls_conn->dd_data;
2080         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2081         struct inet_sock *inet;
2082         struct ipv6_pinfo *np;
2083         struct sock *sk;
2084         int len;
2085
2086         switch(param) {
2087         case ISCSI_PARAM_CONN_PORT:
2088                 if (!tcp_conn->sock)
2089                         return -EINVAL;
2090
2091                 inet = inet_sk(tcp_conn->sock->sk);
2092                 len = sprintf(buf, "%hu\n", be16_to_cpu(inet->dport));
2093                 break;
2094         case ISCSI_PARAM_CONN_ADDRESS:
2095                 if (!tcp_conn->sock)
2096                         return -EINVAL;
2097
2098                 sk = tcp_conn->sock->sk;
2099                 if (sk->sk_family == PF_INET) {
2100                         inet = inet_sk(sk);
2101                         len = sprintf(buf, NIPQUAD_FMT "\n",
2102                                       NIPQUAD(inet->daddr));
2103                 } else {
2104                         np = inet6_sk(sk);
2105                         len = sprintf(buf, NIP6_FMT "\n", NIP6(np->daddr));
2106                 }
2107                 break;
2108         default:
2109                 return iscsi_conn_get_param(cls_conn, param, buf);
2110         }
2111
2112         return len;
2113 }
2114
2115 static void
2116 iscsi_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats)
2117 {
2118         struct iscsi_conn *conn = cls_conn->dd_data;
2119         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2120
2121         stats->txdata_octets = conn->txdata_octets;
2122         stats->rxdata_octets = conn->rxdata_octets;
2123         stats->scsicmd_pdus = conn->scsicmd_pdus_cnt;
2124         stats->dataout_pdus = conn->dataout_pdus_cnt;
2125         stats->scsirsp_pdus = conn->scsirsp_pdus_cnt;
2126         stats->datain_pdus = conn->datain_pdus_cnt;
2127         stats->r2t_pdus = conn->r2t_pdus_cnt;
2128         stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt;
2129         stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt;
2130         stats->custom_length = 3;
2131         strcpy(stats->custom[0].desc, "tx_sendpage_failures");
2132         stats->custom[0].value = tcp_conn->sendpage_failures_cnt;
2133         strcpy(stats->custom[1].desc, "rx_discontiguous_hdr");
2134         stats->custom[1].value = tcp_conn->discontiguous_hdr_cnt;
2135         strcpy(stats->custom[2].desc, "eh_abort_cnt");
2136         stats->custom[2].value = conn->eh_abort_cnt;
2137 }
2138
2139 static struct iscsi_cls_session *
2140 iscsi_tcp_session_create(struct iscsi_transport *iscsit,
2141                          struct scsi_transport_template *scsit,
2142                          uint16_t cmds_max, uint16_t qdepth,
2143                          uint32_t initial_cmdsn, uint32_t *hostno)
2144 {
2145         struct iscsi_cls_session *cls_session;
2146         struct iscsi_session *session;
2147         uint32_t hn;
2148         int cmd_i;
2149
2150         cls_session = iscsi_session_setup(iscsit, scsit, cmds_max, qdepth,
2151                                          sizeof(struct iscsi_tcp_cmd_task),
2152                                          sizeof(struct iscsi_tcp_mgmt_task),
2153                                          initial_cmdsn, &hn);
2154         if (!cls_session)
2155                 return NULL;
2156         *hostno = hn;
2157
2158         session = class_to_transport_session(cls_session);
2159         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2160                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
2161                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2162
2163                 ctask->hdr = &tcp_ctask->hdr;
2164         }
2165
2166         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
2167                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
2168                 struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
2169
2170                 mtask->hdr = &tcp_mtask->hdr;
2171         }
2172
2173         if (iscsi_r2tpool_alloc(class_to_transport_session(cls_session)))
2174                 goto r2tpool_alloc_fail;
2175
2176         return cls_session;
2177
2178 r2tpool_alloc_fail:
2179         iscsi_session_teardown(cls_session);
2180         return NULL;
2181 }
2182
2183 static void iscsi_tcp_session_destroy(struct iscsi_cls_session *cls_session)
2184 {
2185         iscsi_r2tpool_free(class_to_transport_session(cls_session));
2186         iscsi_session_teardown(cls_session);
2187 }
2188
2189 static int iscsi_tcp_slave_configure(struct scsi_device *sdev)
2190 {
2191         blk_queue_dma_alignment(sdev->request_queue, 0);
2192         return 0;
2193 }
2194
2195 static struct scsi_host_template iscsi_sht = {
2196         .name                   = "iSCSI Initiator over TCP/IP",
2197         .queuecommand           = iscsi_queuecommand,
2198         .change_queue_depth     = iscsi_change_queue_depth,
2199         .can_queue              = ISCSI_DEF_XMIT_CMDS_MAX - 1,
2200         .sg_tablesize           = ISCSI_SG_TABLESIZE,
2201         .max_sectors            = 0xFFFF,
2202         .cmd_per_lun            = ISCSI_DEF_CMD_PER_LUN,
2203         .eh_abort_handler       = iscsi_eh_abort,
2204         .eh_host_reset_handler  = iscsi_eh_host_reset,
2205         .use_clustering         = DISABLE_CLUSTERING,
2206         .slave_configure        = iscsi_tcp_slave_configure,
2207         .proc_name              = "iscsi_tcp",
2208         .this_id                = -1,
2209 };
2210
2211 static struct iscsi_transport iscsi_tcp_transport = {
2212         .owner                  = THIS_MODULE,
2213         .name                   = "tcp",
2214         .caps                   = CAP_RECOVERY_L0 | CAP_MULTI_R2T | CAP_HDRDGST
2215                                   | CAP_DATADGST,
2216         .param_mask             = ISCSI_MAX_RECV_DLENGTH |
2217                                   ISCSI_MAX_XMIT_DLENGTH |
2218                                   ISCSI_HDRDGST_EN |
2219                                   ISCSI_DATADGST_EN |
2220                                   ISCSI_INITIAL_R2T_EN |
2221                                   ISCSI_MAX_R2T |
2222                                   ISCSI_IMM_DATA_EN |
2223                                   ISCSI_FIRST_BURST |
2224                                   ISCSI_MAX_BURST |
2225                                   ISCSI_PDU_INORDER_EN |
2226                                   ISCSI_DATASEQ_INORDER_EN |
2227                                   ISCSI_ERL |
2228                                   ISCSI_CONN_PORT |
2229                                   ISCSI_CONN_ADDRESS |
2230                                   ISCSI_EXP_STATSN |
2231                                   ISCSI_PERSISTENT_PORT |
2232                                   ISCSI_PERSISTENT_ADDRESS |
2233                                   ISCSI_TARGET_NAME | ISCSI_TPGT |
2234                                   ISCSI_USERNAME | ISCSI_PASSWORD |
2235                                   ISCSI_USERNAME_IN | ISCSI_PASSWORD_IN,
2236         .host_param_mask        = ISCSI_HOST_HWADDRESS |
2237                                   ISCSI_HOST_INITIATOR_NAME,
2238         .host_template          = &iscsi_sht,
2239         .conndata_size          = sizeof(struct iscsi_conn),
2240         .max_conn               = 1,
2241         .max_cmd_len            = ISCSI_TCP_MAX_CMD_LEN,
2242         /* session management */
2243         .create_session         = iscsi_tcp_session_create,
2244         .destroy_session        = iscsi_tcp_session_destroy,
2245         /* connection management */
2246         .create_conn            = iscsi_tcp_conn_create,
2247         .bind_conn              = iscsi_tcp_conn_bind,
2248         .destroy_conn           = iscsi_tcp_conn_destroy,
2249         .set_param              = iscsi_conn_set_param,
2250         .get_conn_param         = iscsi_tcp_conn_get_param,
2251         .get_session_param      = iscsi_session_get_param,
2252         .start_conn             = iscsi_conn_start,
2253         .stop_conn              = iscsi_tcp_conn_stop,
2254         /* iscsi host params */
2255         .get_host_param         = iscsi_host_get_param,
2256         .set_host_param         = iscsi_host_set_param,
2257         /* IO */
2258         .send_pdu               = iscsi_conn_send_pdu,
2259         .get_stats              = iscsi_conn_get_stats,
2260         .init_cmd_task          = iscsi_tcp_cmd_init,
2261         .init_mgmt_task         = iscsi_tcp_mgmt_init,
2262         .xmit_cmd_task          = iscsi_tcp_ctask_xmit,
2263         .xmit_mgmt_task         = iscsi_tcp_mtask_xmit,
2264         .cleanup_cmd_task       = iscsi_tcp_cleanup_ctask,
2265         /* recovery */
2266         .session_recovery_timedout = iscsi_session_recovery_timedout,
2267 };
2268
2269 static int __init
2270 iscsi_tcp_init(void)
2271 {
2272         if (iscsi_max_lun < 1) {
2273                 printk(KERN_ERR "iscsi_tcp: Invalid max_lun value of %u\n",
2274                        iscsi_max_lun);
2275                 return -EINVAL;
2276         }
2277         iscsi_tcp_transport.max_lun = iscsi_max_lun;
2278
2279         if (!iscsi_register_transport(&iscsi_tcp_transport))
2280                 return -ENODEV;
2281
2282         return 0;
2283 }
2284
2285 static void __exit
2286 iscsi_tcp_exit(void)
2287 {
2288         iscsi_unregister_transport(&iscsi_tcp_transport);
2289 }
2290
2291 module_init(iscsi_tcp_init);
2292 module_exit(iscsi_tcp_exit);