]> Pileus Git - ~andy/linux/blob - drivers/block/drbd/drbd_nl.c
drbd: prepare for new striped layout of activity log
[~andy/linux] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include "drbd_nla.h"
79 #include <linux/genl_magic_func.h>
80
81 /* used blkdev_get_by_path, to claim our meta data device(s) */
82 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
83
84 /* Configuration is strictly serialized, because generic netlink message
85  * processing is strictly serialized by the genl_lock().
86  * Which means we can use one static global drbd_config_context struct.
87  */
88 static struct drbd_config_context {
89         /* assigned from drbd_genlmsghdr */
90         unsigned int minor;
91         /* assigned from request attributes, if present */
92         unsigned int volume;
93 #define VOLUME_UNSPECIFIED              (-1U)
94         /* pointer into the request skb,
95          * limited lifetime! */
96         char *resource_name;
97         struct nlattr *my_addr;
98         struct nlattr *peer_addr;
99
100         /* reply buffer */
101         struct sk_buff *reply_skb;
102         /* pointer into reply buffer */
103         struct drbd_genlmsghdr *reply_dh;
104         /* resolved from attributes, if possible */
105         struct drbd_conf *mdev;
106         struct drbd_tconn *tconn;
107 } adm_ctx;
108
109 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
110 {
111         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
112         if (genlmsg_reply(skb, info))
113                 printk(KERN_ERR "drbd: error sending genl reply\n");
114 }
115
116 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
117  * reason it could fail was no space in skb, and there are 4k available. */
118 int drbd_msg_put_info(const char *info)
119 {
120         struct sk_buff *skb = adm_ctx.reply_skb;
121         struct nlattr *nla;
122         int err = -EMSGSIZE;
123
124         if (!info || !info[0])
125                 return 0;
126
127         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
128         if (!nla)
129                 return err;
130
131         err = nla_put_string(skb, T_info_text, info);
132         if (err) {
133                 nla_nest_cancel(skb, nla);
134                 return err;
135         } else
136                 nla_nest_end(skb, nla);
137         return 0;
138 }
139
140 /* This would be a good candidate for a "pre_doit" hook,
141  * and per-family private info->pointers.
142  * But we need to stay compatible with older kernels.
143  * If it returns successfully, adm_ctx members are valid.
144  */
145 #define DRBD_ADM_NEED_MINOR     1
146 #define DRBD_ADM_NEED_RESOURCE  2
147 #define DRBD_ADM_NEED_CONNECTION 4
148 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
149                 unsigned flags)
150 {
151         struct drbd_genlmsghdr *d_in = info->userhdr;
152         const u8 cmd = info->genlhdr->cmd;
153         int err;
154
155         memset(&adm_ctx, 0, sizeof(adm_ctx));
156
157         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
158         if (cmd != DRBD_ADM_GET_STATUS && !capable(CAP_NET_ADMIN))
159                return -EPERM;
160
161         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
162         if (!adm_ctx.reply_skb) {
163                 err = -ENOMEM;
164                 goto fail;
165         }
166
167         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
168                                         info, &drbd_genl_family, 0, cmd);
169         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
170          * but anyways */
171         if (!adm_ctx.reply_dh) {
172                 err = -ENOMEM;
173                 goto fail;
174         }
175
176         adm_ctx.reply_dh->minor = d_in->minor;
177         adm_ctx.reply_dh->ret_code = NO_ERROR;
178
179         adm_ctx.volume = VOLUME_UNSPECIFIED;
180         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
181                 struct nlattr *nla;
182                 /* parse and validate only */
183                 err = drbd_cfg_context_from_attrs(NULL, info);
184                 if (err)
185                         goto fail;
186
187                 /* It was present, and valid,
188                  * copy it over to the reply skb. */
189                 err = nla_put_nohdr(adm_ctx.reply_skb,
190                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
191                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
192                 if (err)
193                         goto fail;
194
195                 /* and assign stuff to the global adm_ctx */
196                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
197                 if (nla)
198                         adm_ctx.volume = nla_get_u32(nla);
199                 nla = nested_attr_tb[__nla_type(T_ctx_resource_name)];
200                 if (nla)
201                         adm_ctx.resource_name = nla_data(nla);
202                 adm_ctx.my_addr = nested_attr_tb[__nla_type(T_ctx_my_addr)];
203                 adm_ctx.peer_addr = nested_attr_tb[__nla_type(T_ctx_peer_addr)];
204                 if ((adm_ctx.my_addr &&
205                      nla_len(adm_ctx.my_addr) > sizeof(adm_ctx.tconn->my_addr)) ||
206                     (adm_ctx.peer_addr &&
207                      nla_len(adm_ctx.peer_addr) > sizeof(adm_ctx.tconn->peer_addr))) {
208                         err = -EINVAL;
209                         goto fail;
210                 }
211         }
212
213         adm_ctx.minor = d_in->minor;
214         adm_ctx.mdev = minor_to_mdev(d_in->minor);
215         adm_ctx.tconn = conn_get_by_name(adm_ctx.resource_name);
216
217         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
218                 drbd_msg_put_info("unknown minor");
219                 return ERR_MINOR_INVALID;
220         }
221         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_RESOURCE)) {
222                 drbd_msg_put_info("unknown resource");
223                 return ERR_INVALID_REQUEST;
224         }
225
226         if (flags & DRBD_ADM_NEED_CONNECTION) {
227                 if (adm_ctx.tconn && !(flags & DRBD_ADM_NEED_RESOURCE)) {
228                         drbd_msg_put_info("no resource name expected");
229                         return ERR_INVALID_REQUEST;
230                 }
231                 if (adm_ctx.mdev) {
232                         drbd_msg_put_info("no minor number expected");
233                         return ERR_INVALID_REQUEST;
234                 }
235                 if (adm_ctx.my_addr && adm_ctx.peer_addr)
236                         adm_ctx.tconn = conn_get_by_addrs(nla_data(adm_ctx.my_addr),
237                                                           nla_len(adm_ctx.my_addr),
238                                                           nla_data(adm_ctx.peer_addr),
239                                                           nla_len(adm_ctx.peer_addr));
240                 if (!adm_ctx.tconn) {
241                         drbd_msg_put_info("unknown connection");
242                         return ERR_INVALID_REQUEST;
243                 }
244         }
245
246         /* some more paranoia, if the request was over-determined */
247         if (adm_ctx.mdev && adm_ctx.tconn &&
248             adm_ctx.mdev->tconn != adm_ctx.tconn) {
249                 pr_warning("request: minor=%u, resource=%s; but that minor belongs to connection %s\n",
250                                 adm_ctx.minor, adm_ctx.resource_name,
251                                 adm_ctx.mdev->tconn->name);
252                 drbd_msg_put_info("minor exists in different resource");
253                 return ERR_INVALID_REQUEST;
254         }
255         if (adm_ctx.mdev &&
256             adm_ctx.volume != VOLUME_UNSPECIFIED &&
257             adm_ctx.volume != adm_ctx.mdev->vnr) {
258                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
259                                 adm_ctx.minor, adm_ctx.volume,
260                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
261                 drbd_msg_put_info("minor exists as different volume");
262                 return ERR_INVALID_REQUEST;
263         }
264
265         return NO_ERROR;
266
267 fail:
268         nlmsg_free(adm_ctx.reply_skb);
269         adm_ctx.reply_skb = NULL;
270         return err;
271 }
272
273 static int drbd_adm_finish(struct genl_info *info, int retcode)
274 {
275         if (adm_ctx.tconn) {
276                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
277                 adm_ctx.tconn = NULL;
278         }
279
280         if (!adm_ctx.reply_skb)
281                 return -ENOMEM;
282
283         adm_ctx.reply_dh->ret_code = retcode;
284         drbd_adm_send_reply(adm_ctx.reply_skb, info);
285         return 0;
286 }
287
288 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
289 {
290         char *afs;
291
292         /* FIXME: A future version will not allow this case. */
293         if (tconn->my_addr_len == 0 || tconn->peer_addr_len == 0)
294                 return;
295
296         switch (((struct sockaddr *)&tconn->peer_addr)->sa_family) {
297         case AF_INET6:
298                 afs = "ipv6";
299                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
300                          &((struct sockaddr_in6 *)&tconn->peer_addr)->sin6_addr);
301                 break;
302         case AF_INET:
303                 afs = "ipv4";
304                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
305                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
306                 break;
307         default:
308                 afs = "ssocks";
309                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
310                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
311         }
312         snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
313 }
314
315 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
316 {
317         char *envp[] = { "HOME=/",
318                         "TERM=linux",
319                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
320                          (char[20]) { }, /* address family */
321                          (char[60]) { }, /* address */
322                         NULL };
323         char mb[12];
324         char *argv[] = {usermode_helper, cmd, mb, NULL };
325         struct drbd_tconn *tconn = mdev->tconn;
326         struct sib_info sib;
327         int ret;
328
329         if (current == tconn->worker.task)
330                 set_bit(CALLBACK_PENDING, &tconn->flags);
331
332         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
333         setup_khelper_env(tconn, envp);
334
335         /* The helper may take some time.
336          * write out any unsynced meta data changes now */
337         drbd_md_sync(mdev);
338
339         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
340         sib.sib_reason = SIB_HELPER_PRE;
341         sib.helper_name = cmd;
342         drbd_bcast_event(mdev, &sib);
343         ret = call_usermodehelper(usermode_helper, argv, envp, UMH_WAIT_PROC);
344         if (ret)
345                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
346                                 usermode_helper, cmd, mb,
347                                 (ret >> 8) & 0xff, ret);
348         else
349                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
350                                 usermode_helper, cmd, mb,
351                                 (ret >> 8) & 0xff, ret);
352         sib.sib_reason = SIB_HELPER_POST;
353         sib.helper_exit_code = ret;
354         drbd_bcast_event(mdev, &sib);
355
356         if (current == tconn->worker.task)
357                 clear_bit(CALLBACK_PENDING, &tconn->flags);
358
359         if (ret < 0) /* Ignore any ERRNOs we got. */
360                 ret = 0;
361
362         return ret;
363 }
364
365 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
366 {
367         char *envp[] = { "HOME=/",
368                         "TERM=linux",
369                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
370                          (char[20]) { }, /* address family */
371                          (char[60]) { }, /* address */
372                         NULL };
373         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
374         int ret;
375
376         setup_khelper_env(tconn, envp);
377         conn_md_sync(tconn);
378
379         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
380         /* TODO: conn_bcast_event() ?? */
381
382         ret = call_usermodehelper(usermode_helper, argv, envp, UMH_WAIT_PROC);
383         if (ret)
384                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
385                           usermode_helper, cmd, tconn->name,
386                           (ret >> 8) & 0xff, ret);
387         else
388                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
389                           usermode_helper, cmd, tconn->name,
390                           (ret >> 8) & 0xff, ret);
391         /* TODO: conn_bcast_event() ?? */
392
393         if (ret < 0) /* Ignore any ERRNOs we got. */
394                 ret = 0;
395
396         return ret;
397 }
398
399 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
400 {
401         enum drbd_fencing_p fp = FP_NOT_AVAIL;
402         struct drbd_conf *mdev;
403         int vnr;
404
405         rcu_read_lock();
406         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
407                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
408                         fp = max_t(enum drbd_fencing_p, fp,
409                                    rcu_dereference(mdev->ldev->disk_conf)->fencing);
410                         put_ldev(mdev);
411                 }
412         }
413         rcu_read_unlock();
414
415         return fp;
416 }
417
418 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
419 {
420         union drbd_state mask = { };
421         union drbd_state val = { };
422         enum drbd_fencing_p fp;
423         char *ex_to_string;
424         int r;
425
426         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
427                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
428                 return false;
429         }
430
431         fp = highest_fencing_policy(tconn);
432         switch (fp) {
433         case FP_NOT_AVAIL:
434                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
435                 goto out;
436         case FP_DONT_CARE:
437                 return true;
438         default: ;
439         }
440
441         r = conn_khelper(tconn, "fence-peer");
442
443         switch ((r>>8) & 0xff) {
444         case 3: /* peer is inconsistent */
445                 ex_to_string = "peer is inconsistent or worse";
446                 mask.pdsk = D_MASK;
447                 val.pdsk = D_INCONSISTENT;
448                 break;
449         case 4: /* peer got outdated, or was already outdated */
450                 ex_to_string = "peer was fenced";
451                 mask.pdsk = D_MASK;
452                 val.pdsk = D_OUTDATED;
453                 break;
454         case 5: /* peer was down */
455                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
456                         /* we will(have) create(d) a new UUID anyways... */
457                         ex_to_string = "peer is unreachable, assumed to be dead";
458                         mask.pdsk = D_MASK;
459                         val.pdsk = D_OUTDATED;
460                 } else {
461                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
462                 }
463                 break;
464         case 6: /* Peer is primary, voluntarily outdate myself.
465                  * This is useful when an unconnected R_SECONDARY is asked to
466                  * become R_PRIMARY, but finds the other peer being active. */
467                 ex_to_string = "peer is active";
468                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
469                 mask.disk = D_MASK;
470                 val.disk = D_OUTDATED;
471                 break;
472         case 7:
473                 if (fp != FP_STONITH)
474                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
475                 ex_to_string = "peer was stonithed";
476                 mask.pdsk = D_MASK;
477                 val.pdsk = D_OUTDATED;
478                 break;
479         default:
480                 /* The script is broken ... */
481                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
482                 return false; /* Eventually leave IO frozen */
483         }
484
485         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
486                   (r>>8) & 0xff, ex_to_string);
487
488  out:
489
490         /* Not using
491            conn_request_state(tconn, mask, val, CS_VERBOSE);
492            here, because we might were able to re-establish the connection in the
493            meantime. */
494         spin_lock_irq(&tconn->req_lock);
495         if (tconn->cstate < C_WF_REPORT_PARAMS && !test_bit(STATE_SENT, &tconn->flags))
496                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
497         spin_unlock_irq(&tconn->req_lock);
498
499         return conn_highest_pdsk(tconn) <= D_OUTDATED;
500 }
501
502 static int _try_outdate_peer_async(void *data)
503 {
504         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
505
506         conn_try_outdate_peer(tconn);
507
508         kref_put(&tconn->kref, &conn_destroy);
509         return 0;
510 }
511
512 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
513 {
514         struct task_struct *opa;
515
516         kref_get(&tconn->kref);
517         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
518         if (IS_ERR(opa)) {
519                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
520                 kref_put(&tconn->kref, &conn_destroy);
521         }
522 }
523
524 enum drbd_state_rv
525 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
526 {
527         const int max_tries = 4;
528         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
529         struct net_conf *nc;
530         int try = 0;
531         int forced = 0;
532         union drbd_state mask, val;
533
534         if (new_role == R_PRIMARY)
535                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
536
537         mutex_lock(mdev->state_mutex);
538
539         mask.i = 0; mask.role = R_MASK;
540         val.i  = 0; val.role  = new_role;
541
542         while (try++ < max_tries) {
543                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
544
545                 /* in case we first succeeded to outdate,
546                  * but now suddenly could establish a connection */
547                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
548                         val.pdsk = 0;
549                         mask.pdsk = 0;
550                         continue;
551                 }
552
553                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
554                     (mdev->state.disk < D_UP_TO_DATE &&
555                      mdev->state.disk >= D_INCONSISTENT)) {
556                         mask.disk = D_MASK;
557                         val.disk  = D_UP_TO_DATE;
558                         forced = 1;
559                         continue;
560                 }
561
562                 if (rv == SS_NO_UP_TO_DATE_DISK &&
563                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
564                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
565
566                         if (conn_try_outdate_peer(mdev->tconn)) {
567                                 val.disk = D_UP_TO_DATE;
568                                 mask.disk = D_MASK;
569                         }
570                         continue;
571                 }
572
573                 if (rv == SS_NOTHING_TO_DO)
574                         goto out;
575                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
576                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
577                                 dev_warn(DEV, "Forced into split brain situation!\n");
578                                 mask.pdsk = D_MASK;
579                                 val.pdsk  = D_OUTDATED;
580
581                         }
582                         continue;
583                 }
584                 if (rv == SS_TWO_PRIMARIES) {
585                         /* Maybe the peer is detected as dead very soon...
586                            retry at most once more in this case. */
587                         int timeo;
588                         rcu_read_lock();
589                         nc = rcu_dereference(mdev->tconn->net_conf);
590                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
591                         rcu_read_unlock();
592                         schedule_timeout_interruptible(timeo);
593                         if (try < max_tries)
594                                 try = max_tries - 1;
595                         continue;
596                 }
597                 if (rv < SS_SUCCESS) {
598                         rv = _drbd_request_state(mdev, mask, val,
599                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
600                         if (rv < SS_SUCCESS)
601                                 goto out;
602                 }
603                 break;
604         }
605
606         if (rv < SS_SUCCESS)
607                 goto out;
608
609         if (forced)
610                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
611
612         /* Wait until nothing is on the fly :) */
613         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
614
615         /* FIXME also wait for all pending P_BARRIER_ACK? */
616
617         if (new_role == R_SECONDARY) {
618                 set_disk_ro(mdev->vdisk, true);
619                 if (get_ldev(mdev)) {
620                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
621                         put_ldev(mdev);
622                 }
623         } else {
624                 mutex_lock(&mdev->tconn->conf_update);
625                 nc = mdev->tconn->net_conf;
626                 if (nc)
627                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
628                 mutex_unlock(&mdev->tconn->conf_update);
629
630                 set_disk_ro(mdev->vdisk, false);
631                 if (get_ldev(mdev)) {
632                         if (((mdev->state.conn < C_CONNECTED ||
633                                mdev->state.pdsk <= D_FAILED)
634                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
635                                 drbd_uuid_new_current(mdev);
636
637                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
638                         put_ldev(mdev);
639                 }
640         }
641
642         /* writeout of activity log covered areas of the bitmap
643          * to stable storage done in after state change already */
644
645         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
646                 /* if this was forced, we should consider sync */
647                 if (forced)
648                         drbd_send_uuids(mdev);
649                 drbd_send_current_state(mdev);
650         }
651
652         drbd_md_sync(mdev);
653
654         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
655 out:
656         mutex_unlock(mdev->state_mutex);
657         return rv;
658 }
659
660 static const char *from_attrs_err_to_txt(int err)
661 {
662         return  err == -ENOMSG ? "required attribute missing" :
663                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
664                 err == -EEXIST ? "can not change invariant setting" :
665                 "invalid attribute value";
666 }
667
668 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
669 {
670         struct set_role_parms parms;
671         int err;
672         enum drbd_ret_code retcode;
673
674         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
675         if (!adm_ctx.reply_skb)
676                 return retcode;
677         if (retcode != NO_ERROR)
678                 goto out;
679
680         memset(&parms, 0, sizeof(parms));
681         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
682                 err = set_role_parms_from_attrs(&parms, info);
683                 if (err) {
684                         retcode = ERR_MANDATORY_TAG;
685                         drbd_msg_put_info(from_attrs_err_to_txt(err));
686                         goto out;
687                 }
688         }
689
690         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
691                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
692         else
693                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
694 out:
695         drbd_adm_finish(info, retcode);
696         return 0;
697 }
698
699 /* Initializes the md.*_offset members, so we are able to find
700  * the on disk meta data.
701  *
702  * We currently have two possible layouts:
703  * external:
704  *   |----------- md_size_sect ------------------|
705  *   [ 4k superblock ][ activity log ][  Bitmap  ]
706  *   | al_offset == 8 |
707  *   | bm_offset = al_offset + X      |
708  *  ==> bitmap sectors = md_size_sect - bm_offset
709  *
710  * internal:
711  *            |----------- md_size_sect ------------------|
712  * [data.....][  Bitmap  ][ activity log ][ 4k superblock ]
713  *                        | al_offset < 0 |
714  *            | bm_offset = al_offset - Y |
715  *  ==> bitmap sectors = Y = al_offset - bm_offset
716  *
717  *  Activity log size used to be fixed 32kB,
718  *  but is about to become configurable.
719  */
720 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
721                                        struct drbd_backing_dev *bdev)
722 {
723         sector_t md_size_sect = 0;
724         unsigned int al_size_sect = MD_32kB_SECT;
725         int meta_dev_idx;
726
727         rcu_read_lock();
728         meta_dev_idx = rcu_dereference(bdev->disk_conf)->meta_dev_idx;
729
730         bdev->md.md_offset = drbd_md_ss(bdev);
731
732         switch (meta_dev_idx) {
733         default:
734                 /* v07 style fixed size indexed meta data */
735                 bdev->md.md_size_sect = MD_128MB_SECT;
736                 bdev->md.al_offset = MD_4kB_SECT;
737                 bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
738                 break;
739         case DRBD_MD_INDEX_FLEX_EXT:
740                 /* just occupy the full device; unit: sectors */
741                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
742                 bdev->md.al_offset = MD_4kB_SECT;
743                 bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
744                 break;
745         case DRBD_MD_INDEX_INTERNAL:
746         case DRBD_MD_INDEX_FLEX_INT:
747                 /* al size is still fixed */
748                 bdev->md.al_offset = -al_size_sect;
749                 /* we need (slightly less than) ~ this much bitmap sectors: */
750                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
751                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
752                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
753                 md_size_sect = ALIGN(md_size_sect, 8);
754
755                 /* plus the "drbd meta data super block",
756                  * and the activity log; */
757                 md_size_sect += MD_4kB_SECT + al_size_sect;
758
759                 bdev->md.md_size_sect = md_size_sect;
760                 /* bitmap offset is adjusted by 'super' block size */
761                 bdev->md.bm_offset   = -md_size_sect + MD_4kB_SECT;
762                 break;
763         }
764         rcu_read_unlock();
765 }
766
767 /* input size is expected to be in KB */
768 char *ppsize(char *buf, unsigned long long size)
769 {
770         /* Needs 9 bytes at max including trailing NUL:
771          * -1ULL ==> "16384 EB" */
772         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
773         int base = 0;
774         while (size >= 10000 && base < sizeof(units)-1) {
775                 /* shift + round */
776                 size = (size >> 10) + !!(size & (1<<9));
777                 base++;
778         }
779         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
780
781         return buf;
782 }
783
784 /* there is still a theoretical deadlock when called from receiver
785  * on an D_INCONSISTENT R_PRIMARY:
786  *  remote READ does inc_ap_bio, receiver would need to receive answer
787  *  packet from remote to dec_ap_bio again.
788  *  receiver receive_sizes(), comes here,
789  *  waits for ap_bio_cnt == 0. -> deadlock.
790  * but this cannot happen, actually, because:
791  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
792  *  (not connected, or bad/no disk on peer):
793  *  see drbd_fail_request_early, ap_bio_cnt is zero.
794  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
795  *  peer may not initiate a resize.
796  */
797 /* Note these are not to be confused with
798  * drbd_adm_suspend_io/drbd_adm_resume_io,
799  * which are (sub) state changes triggered by admin (drbdsetup),
800  * and can be long lived.
801  * This changes an mdev->flag, is triggered by drbd internals,
802  * and should be short-lived. */
803 void drbd_suspend_io(struct drbd_conf *mdev)
804 {
805         set_bit(SUSPEND_IO, &mdev->flags);
806         if (drbd_suspended(mdev))
807                 return;
808         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
809 }
810
811 void drbd_resume_io(struct drbd_conf *mdev)
812 {
813         clear_bit(SUSPEND_IO, &mdev->flags);
814         wake_up(&mdev->misc_wait);
815 }
816
817 /**
818  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
819  * @mdev:       DRBD device.
820  *
821  * Returns 0 on success, negative return values indicate errors.
822  * You should call drbd_md_sync() after calling this function.
823  */
824 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
825 {
826         sector_t prev_first_sect, prev_size; /* previous meta location */
827         sector_t la_size, u_size;
828         sector_t size;
829         char ppb[10];
830
831         int md_moved, la_size_changed;
832         enum determine_dev_size rv = unchanged;
833
834         /* race:
835          * application request passes inc_ap_bio,
836          * but then cannot get an AL-reference.
837          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
838          *
839          * to avoid that:
840          * Suspend IO right here.
841          * still lock the act_log to not trigger ASSERTs there.
842          */
843         drbd_suspend_io(mdev);
844
845         /* no wait necessary anymore, actually we could assert that */
846         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
847
848         prev_first_sect = drbd_md_first_sector(mdev->ldev);
849         prev_size = mdev->ldev->md.md_size_sect;
850         la_size = mdev->ldev->md.la_size_sect;
851
852         /* TODO: should only be some assert here, not (re)init... */
853         drbd_md_set_sector_offsets(mdev, mdev->ldev);
854
855         rcu_read_lock();
856         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
857         rcu_read_unlock();
858         size = drbd_new_dev_size(mdev, mdev->ldev, u_size, flags & DDSF_FORCED);
859
860         if (drbd_get_capacity(mdev->this_bdev) != size ||
861             drbd_bm_capacity(mdev) != size) {
862                 int err;
863                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
864                 if (unlikely(err)) {
865                         /* currently there is only one error: ENOMEM! */
866                         size = drbd_bm_capacity(mdev)>>1;
867                         if (size == 0) {
868                                 dev_err(DEV, "OUT OF MEMORY! "
869                                     "Could not allocate bitmap!\n");
870                         } else {
871                                 dev_err(DEV, "BM resizing failed. "
872                                     "Leaving size unchanged at size = %lu KB\n",
873                                     (unsigned long)size);
874                         }
875                         rv = dev_size_error;
876                 }
877                 /* racy, see comments above. */
878                 drbd_set_my_capacity(mdev, size);
879                 mdev->ldev->md.la_size_sect = size;
880                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
881                      (unsigned long long)size>>1);
882         }
883         if (rv == dev_size_error)
884                 goto out;
885
886         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
887
888         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
889                 || prev_size       != mdev->ldev->md.md_size_sect;
890
891         if (la_size_changed || md_moved) {
892                 int err;
893
894                 drbd_al_shrink(mdev); /* All extents inactive. */
895                 dev_info(DEV, "Writing the whole bitmap, %s\n",
896                          la_size_changed && md_moved ? "size changed and md moved" :
897                          la_size_changed ? "size changed" : "md moved");
898                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
899                 err = drbd_bitmap_io(mdev, md_moved ? &drbd_bm_write_all : &drbd_bm_write,
900                                      "size changed", BM_LOCKED_MASK);
901                 if (err) {
902                         rv = dev_size_error;
903                         goto out;
904                 }
905                 drbd_md_mark_dirty(mdev);
906         }
907
908         if (size > la_size)
909                 rv = grew;
910         if (size < la_size)
911                 rv = shrunk;
912 out:
913         lc_unlock(mdev->act_log);
914         wake_up(&mdev->al_wait);
915         drbd_resume_io(mdev);
916
917         return rv;
918 }
919
920 sector_t
921 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev,
922                   sector_t u_size, int assume_peer_has_space)
923 {
924         sector_t p_size = mdev->p_size;   /* partner's disk size. */
925         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
926         sector_t m_size; /* my size */
927         sector_t size = 0;
928
929         m_size = drbd_get_max_capacity(bdev);
930
931         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
932                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
933                 p_size = m_size;
934         }
935
936         if (p_size && m_size) {
937                 size = min_t(sector_t, p_size, m_size);
938         } else {
939                 if (la_size) {
940                         size = la_size;
941                         if (m_size && m_size < size)
942                                 size = m_size;
943                         if (p_size && p_size < size)
944                                 size = p_size;
945                 } else {
946                         if (m_size)
947                                 size = m_size;
948                         if (p_size)
949                                 size = p_size;
950                 }
951         }
952
953         if (size == 0)
954                 dev_err(DEV, "Both nodes diskless!\n");
955
956         if (u_size) {
957                 if (u_size > size)
958                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
959                             (unsigned long)u_size>>1, (unsigned long)size>>1);
960                 else
961                         size = u_size;
962         }
963
964         return size;
965 }
966
967 /**
968  * drbd_check_al_size() - Ensures that the AL is of the right size
969  * @mdev:       DRBD device.
970  *
971  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
972  * failed, and 0 on success. You should call drbd_md_sync() after you called
973  * this function.
974  */
975 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
976 {
977         struct lru_cache *n, *t;
978         struct lc_element *e;
979         unsigned int in_use;
980         int i;
981
982         if (mdev->act_log &&
983             mdev->act_log->nr_elements == dc->al_extents)
984                 return 0;
985
986         in_use = 0;
987         t = mdev->act_log;
988         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
989                 dc->al_extents, sizeof(struct lc_element), 0);
990
991         if (n == NULL) {
992                 dev_err(DEV, "Cannot allocate act_log lru!\n");
993                 return -ENOMEM;
994         }
995         spin_lock_irq(&mdev->al_lock);
996         if (t) {
997                 for (i = 0; i < t->nr_elements; i++) {
998                         e = lc_element_by_index(t, i);
999                         if (e->refcnt)
1000                                 dev_err(DEV, "refcnt(%d)==%d\n",
1001                                     e->lc_number, e->refcnt);
1002                         in_use += e->refcnt;
1003                 }
1004         }
1005         if (!in_use)
1006                 mdev->act_log = n;
1007         spin_unlock_irq(&mdev->al_lock);
1008         if (in_use) {
1009                 dev_err(DEV, "Activity log still in use!\n");
1010                 lc_destroy(n);
1011                 return -EBUSY;
1012         } else {
1013                 if (t)
1014                         lc_destroy(t);
1015         }
1016         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
1017         return 0;
1018 }
1019
1020 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
1021 {
1022         struct request_queue * const q = mdev->rq_queue;
1023         unsigned int max_hw_sectors = max_bio_size >> 9;
1024         unsigned int max_segments = 0;
1025
1026         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1027                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1028
1029                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
1030                 rcu_read_lock();
1031                 max_segments = rcu_dereference(mdev->ldev->disk_conf)->max_bio_bvecs;
1032                 rcu_read_unlock();
1033                 put_ldev(mdev);
1034         }
1035
1036         blk_queue_logical_block_size(q, 512);
1037         blk_queue_max_hw_sectors(q, max_hw_sectors);
1038         /* This is the workaround for "bio would need to, but cannot, be split" */
1039         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1040         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
1041
1042         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1043                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1044
1045                 blk_queue_stack_limits(q, b);
1046
1047                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
1048                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1049                                  q->backing_dev_info.ra_pages,
1050                                  b->backing_dev_info.ra_pages);
1051                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1052                 }
1053                 put_ldev(mdev);
1054         }
1055 }
1056
1057 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1058 {
1059         unsigned int now, new, local, peer;
1060
1061         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1062         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1063         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1064
1065         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1066                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1067                 mdev->local_max_bio_size = local;
1068                 put_ldev(mdev);
1069         }
1070         local = min(local, DRBD_MAX_BIO_SIZE);
1071
1072         /* We may ignore peer limits if the peer is modern enough.
1073            Because new from 8.3.8 onwards the peer can use multiple
1074            BIOs for a single peer_request */
1075         if (mdev->state.conn >= C_CONNECTED) {
1076                 if (mdev->tconn->agreed_pro_version < 94)
1077                         peer = min( mdev->peer_max_bio_size, DRBD_MAX_SIZE_H80_PACKET);
1078                         /* Correct old drbd (up to 8.3.7) if it believes it can do more than 32KiB */
1079                 else if (mdev->tconn->agreed_pro_version == 94)
1080                         peer = DRBD_MAX_SIZE_H80_PACKET;
1081                 else if (mdev->tconn->agreed_pro_version < 100)
1082                         peer = DRBD_MAX_BIO_SIZE_P95;  /* drbd 8.3.8 onwards, before 8.4.0 */
1083                 else
1084                         peer = DRBD_MAX_BIO_SIZE;
1085         }
1086
1087         new = min(local, peer);
1088
1089         if (mdev->state.role == R_PRIMARY && new < now)
1090                 dev_err(DEV, "ASSERT FAILED new < now; (%u < %u)\n", new, now);
1091
1092         if (new != now)
1093                 dev_info(DEV, "max BIO size = %u\n", new);
1094
1095         drbd_setup_queue_param(mdev, new);
1096 }
1097
1098 /* Starts the worker thread */
1099 static void conn_reconfig_start(struct drbd_tconn *tconn)
1100 {
1101         drbd_thread_start(&tconn->worker);
1102         conn_flush_workqueue(tconn);
1103 }
1104
1105 /* if still unconfigured, stops worker again. */
1106 static void conn_reconfig_done(struct drbd_tconn *tconn)
1107 {
1108         bool stop_threads;
1109         spin_lock_irq(&tconn->req_lock);
1110         stop_threads = conn_all_vols_unconf(tconn) &&
1111                 tconn->cstate == C_STANDALONE;
1112         spin_unlock_irq(&tconn->req_lock);
1113         if (stop_threads) {
1114                 /* asender is implicitly stopped by receiver
1115                  * in conn_disconnect() */
1116                 drbd_thread_stop(&tconn->receiver);
1117                 drbd_thread_stop(&tconn->worker);
1118         }
1119 }
1120
1121 /* Make sure IO is suspended before calling this function(). */
1122 static void drbd_suspend_al(struct drbd_conf *mdev)
1123 {
1124         int s = 0;
1125
1126         if (!lc_try_lock(mdev->act_log)) {
1127                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1128                 return;
1129         }
1130
1131         drbd_al_shrink(mdev);
1132         spin_lock_irq(&mdev->tconn->req_lock);
1133         if (mdev->state.conn < C_CONNECTED)
1134                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1135         spin_unlock_irq(&mdev->tconn->req_lock);
1136         lc_unlock(mdev->act_log);
1137
1138         if (s)
1139                 dev_info(DEV, "Suspended AL updates\n");
1140 }
1141
1142
1143 static bool should_set_defaults(struct genl_info *info)
1144 {
1145         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1146         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1147 }
1148
1149 static void enforce_disk_conf_limits(struct disk_conf *dc)
1150 {
1151         if (dc->al_extents < DRBD_AL_EXTENTS_MIN)
1152                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
1153         if (dc->al_extents > DRBD_AL_EXTENTS_MAX)
1154                 dc->al_extents = DRBD_AL_EXTENTS_MAX;
1155
1156         if (dc->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1157                 dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1158 }
1159
1160 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1161 {
1162         enum drbd_ret_code retcode;
1163         struct drbd_conf *mdev;
1164         struct disk_conf *new_disk_conf, *old_disk_conf;
1165         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1166         int err, fifo_size;
1167
1168         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1169         if (!adm_ctx.reply_skb)
1170                 return retcode;
1171         if (retcode != NO_ERROR)
1172                 goto out;
1173
1174         mdev = adm_ctx.mdev;
1175
1176         /* we also need a disk
1177          * to change the options on */
1178         if (!get_ldev(mdev)) {
1179                 retcode = ERR_NO_DISK;
1180                 goto out;
1181         }
1182
1183         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1184         if (!new_disk_conf) {
1185                 retcode = ERR_NOMEM;
1186                 goto fail;
1187         }
1188
1189         mutex_lock(&mdev->tconn->conf_update);
1190         old_disk_conf = mdev->ldev->disk_conf;
1191         *new_disk_conf = *old_disk_conf;
1192         if (should_set_defaults(info))
1193                 set_disk_conf_defaults(new_disk_conf);
1194
1195         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1196         if (err && err != -ENOMSG) {
1197                 retcode = ERR_MANDATORY_TAG;
1198                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1199         }
1200
1201         if (!expect(new_disk_conf->resync_rate >= 1))
1202                 new_disk_conf->resync_rate = 1;
1203
1204         enforce_disk_conf_limits(new_disk_conf);
1205
1206         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1207         if (fifo_size != mdev->rs_plan_s->size) {
1208                 new_plan = fifo_alloc(fifo_size);
1209                 if (!new_plan) {
1210                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1211                         retcode = ERR_NOMEM;
1212                         goto fail_unlock;
1213                 }
1214         }
1215
1216         drbd_suspend_io(mdev);
1217         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1218         drbd_al_shrink(mdev);
1219         err = drbd_check_al_size(mdev, new_disk_conf);
1220         lc_unlock(mdev->act_log);
1221         wake_up(&mdev->al_wait);
1222         drbd_resume_io(mdev);
1223
1224         if (err) {
1225                 retcode = ERR_NOMEM;
1226                 goto fail_unlock;
1227         }
1228
1229         write_lock_irq(&global_state_lock);
1230         retcode = drbd_resync_after_valid(mdev, new_disk_conf->resync_after);
1231         if (retcode == NO_ERROR) {
1232                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
1233                 drbd_resync_after_changed(mdev);
1234         }
1235         write_unlock_irq(&global_state_lock);
1236
1237         if (retcode != NO_ERROR)
1238                 goto fail_unlock;
1239
1240         if (new_plan) {
1241                 old_plan = mdev->rs_plan_s;
1242                 rcu_assign_pointer(mdev->rs_plan_s, new_plan);
1243         }
1244
1245         mutex_unlock(&mdev->tconn->conf_update);
1246
1247         if (new_disk_conf->al_updates)
1248                 mdev->ldev->md.flags &= ~MDF_AL_DISABLED;
1249         else
1250                 mdev->ldev->md.flags |= MDF_AL_DISABLED;
1251
1252         if (new_disk_conf->md_flushes)
1253                 clear_bit(MD_NO_FUA, &mdev->flags);
1254         else
1255                 set_bit(MD_NO_FUA, &mdev->flags);
1256
1257         drbd_bump_write_ordering(mdev->tconn, WO_bdev_flush);
1258
1259         drbd_md_sync(mdev);
1260
1261         if (mdev->state.conn >= C_CONNECTED)
1262                 drbd_send_sync_param(mdev);
1263
1264         synchronize_rcu();
1265         kfree(old_disk_conf);
1266         kfree(old_plan);
1267         mod_timer(&mdev->request_timer, jiffies + HZ);
1268         goto success;
1269
1270 fail_unlock:
1271         mutex_unlock(&mdev->tconn->conf_update);
1272  fail:
1273         kfree(new_disk_conf);
1274         kfree(new_plan);
1275 success:
1276         put_ldev(mdev);
1277  out:
1278         drbd_adm_finish(info, retcode);
1279         return 0;
1280 }
1281
1282 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1283 {
1284         struct drbd_conf *mdev;
1285         int err;
1286         enum drbd_ret_code retcode;
1287         enum determine_dev_size dd;
1288         sector_t max_possible_sectors;
1289         sector_t min_md_device_sectors;
1290         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1291         struct disk_conf *new_disk_conf = NULL;
1292         struct block_device *bdev;
1293         struct lru_cache *resync_lru = NULL;
1294         struct fifo_buffer *new_plan = NULL;
1295         union drbd_state ns, os;
1296         enum drbd_state_rv rv;
1297         struct net_conf *nc;
1298
1299         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1300         if (!adm_ctx.reply_skb)
1301                 return retcode;
1302         if (retcode != NO_ERROR)
1303                 goto finish;
1304
1305         mdev = adm_ctx.mdev;
1306         conn_reconfig_start(mdev->tconn);
1307
1308         /* if you want to reconfigure, please tear down first */
1309         if (mdev->state.disk > D_DISKLESS) {
1310                 retcode = ERR_DISK_CONFIGURED;
1311                 goto fail;
1312         }
1313         /* It may just now have detached because of IO error.  Make sure
1314          * drbd_ldev_destroy is done already, we may end up here very fast,
1315          * e.g. if someone calls attach from the on-io-error handler,
1316          * to realize a "hot spare" feature (not that I'd recommend that) */
1317         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1318
1319         /* make sure there is no leftover from previous force-detach attempts */
1320         clear_bit(FORCE_DETACH, &mdev->flags);
1321         clear_bit(WAS_IO_ERROR, &mdev->flags);
1322         clear_bit(WAS_READ_ERROR, &mdev->flags);
1323
1324         /* and no leftover from previously aborted resync or verify, either */
1325         mdev->rs_total = 0;
1326         mdev->rs_failed = 0;
1327         atomic_set(&mdev->rs_pending_cnt, 0);
1328
1329         /* allocation not in the IO path, drbdsetup context */
1330         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1331         if (!nbc) {
1332                 retcode = ERR_NOMEM;
1333                 goto fail;
1334         }
1335         spin_lock_init(&nbc->md.uuid_lock);
1336
1337         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1338         if (!new_disk_conf) {
1339                 retcode = ERR_NOMEM;
1340                 goto fail;
1341         }
1342         nbc->disk_conf = new_disk_conf;
1343
1344         set_disk_conf_defaults(new_disk_conf);
1345         err = disk_conf_from_attrs(new_disk_conf, info);
1346         if (err) {
1347                 retcode = ERR_MANDATORY_TAG;
1348                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1349                 goto fail;
1350         }
1351
1352         enforce_disk_conf_limits(new_disk_conf);
1353
1354         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1355         if (!new_plan) {
1356                 retcode = ERR_NOMEM;
1357                 goto fail;
1358         }
1359
1360         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1361                 retcode = ERR_MD_IDX_INVALID;
1362                 goto fail;
1363         }
1364
1365         rcu_read_lock();
1366         nc = rcu_dereference(mdev->tconn->net_conf);
1367         if (nc) {
1368                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1369                         rcu_read_unlock();
1370                         retcode = ERR_STONITH_AND_PROT_A;
1371                         goto fail;
1372                 }
1373         }
1374         rcu_read_unlock();
1375
1376         bdev = blkdev_get_by_path(new_disk_conf->backing_dev,
1377                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1378         if (IS_ERR(bdev)) {
1379                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->backing_dev,
1380                         PTR_ERR(bdev));
1381                 retcode = ERR_OPEN_DISK;
1382                 goto fail;
1383         }
1384         nbc->backing_bdev = bdev;
1385
1386         /*
1387          * meta_dev_idx >= 0: external fixed size, possibly multiple
1388          * drbd sharing one meta device.  TODO in that case, paranoia
1389          * check that [md_bdev, meta_dev_idx] is not yet used by some
1390          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1391          * should check it for you already; but if you don't, or
1392          * someone fooled it, we need to double check here)
1393          */
1394         bdev = blkdev_get_by_path(new_disk_conf->meta_dev,
1395                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1396                                   (new_disk_conf->meta_dev_idx < 0) ?
1397                                   (void *)mdev : (void *)drbd_m_holder);
1398         if (IS_ERR(bdev)) {
1399                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->meta_dev,
1400                         PTR_ERR(bdev));
1401                 retcode = ERR_OPEN_MD_DISK;
1402                 goto fail;
1403         }
1404         nbc->md_bdev = bdev;
1405
1406         if ((nbc->backing_bdev == nbc->md_bdev) !=
1407             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1408              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1409                 retcode = ERR_MD_IDX_INVALID;
1410                 goto fail;
1411         }
1412
1413         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1414                         1, 61, sizeof(struct bm_extent),
1415                         offsetof(struct bm_extent, lce));
1416         if (!resync_lru) {
1417                 retcode = ERR_NOMEM;
1418                 goto fail;
1419         }
1420
1421         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1422         drbd_md_set_sector_offsets(mdev, nbc);
1423
1424         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1425                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1426                         (unsigned long long) drbd_get_max_capacity(nbc),
1427                         (unsigned long long) new_disk_conf->disk_size);
1428                 retcode = ERR_DISK_TOO_SMALL;
1429                 goto fail;
1430         }
1431
1432         if (new_disk_conf->meta_dev_idx < 0) {
1433                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1434                 /* at least one MB, otherwise it does not make sense */
1435                 min_md_device_sectors = (2<<10);
1436         } else {
1437                 max_possible_sectors = DRBD_MAX_SECTORS;
1438                 min_md_device_sectors = MD_128MB_SECT * (new_disk_conf->meta_dev_idx + 1);
1439         }
1440
1441         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1442                 retcode = ERR_MD_DISK_TOO_SMALL;
1443                 dev_warn(DEV, "refusing attach: md-device too small, "
1444                      "at least %llu sectors needed for this meta-disk type\n",
1445                      (unsigned long long) min_md_device_sectors);
1446                 goto fail;
1447         }
1448
1449         /* Make sure the new disk is big enough
1450          * (we may currently be R_PRIMARY with no local disk...) */
1451         if (drbd_get_max_capacity(nbc) <
1452             drbd_get_capacity(mdev->this_bdev)) {
1453                 retcode = ERR_DISK_TOO_SMALL;
1454                 goto fail;
1455         }
1456
1457         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1458
1459         if (nbc->known_size > max_possible_sectors) {
1460                 dev_warn(DEV, "==> truncating very big lower level device "
1461                         "to currently maximum possible %llu sectors <==\n",
1462                         (unsigned long long) max_possible_sectors);
1463                 if (new_disk_conf->meta_dev_idx >= 0)
1464                         dev_warn(DEV, "==>> using internal or flexible "
1465                                       "meta data may help <<==\n");
1466         }
1467
1468         drbd_suspend_io(mdev);
1469         /* also wait for the last barrier ack. */
1470         /* FIXME see also https://daiquiri.linbit/cgi-bin/bugzilla/show_bug.cgi?id=171
1471          * We need a way to either ignore barrier acks for barriers sent before a device
1472          * was attached, or a way to wait for all pending barrier acks to come in.
1473          * As barriers are counted per resource,
1474          * we'd need to suspend io on all devices of a resource.
1475          */
1476         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1477         /* and for any other previously queued work */
1478         drbd_flush_workqueue(mdev);
1479
1480         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1481         retcode = rv;  /* FIXME: Type mismatch. */
1482         drbd_resume_io(mdev);
1483         if (rv < SS_SUCCESS)
1484                 goto fail;
1485
1486         if (!get_ldev_if_state(mdev, D_ATTACHING))
1487                 goto force_diskless;
1488
1489         drbd_md_set_sector_offsets(mdev, nbc);
1490
1491         if (!mdev->bitmap) {
1492                 if (drbd_bm_init(mdev)) {
1493                         retcode = ERR_NOMEM;
1494                         goto force_diskless_dec;
1495                 }
1496         }
1497
1498         retcode = drbd_md_read(mdev, nbc);
1499         if (retcode != NO_ERROR)
1500                 goto force_diskless_dec;
1501
1502         if (mdev->state.conn < C_CONNECTED &&
1503             mdev->state.role == R_PRIMARY &&
1504             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1505                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1506                     (unsigned long long)mdev->ed_uuid);
1507                 retcode = ERR_DATA_NOT_CURRENT;
1508                 goto force_diskless_dec;
1509         }
1510
1511         /* Since we are diskless, fix the activity log first... */
1512         if (drbd_check_al_size(mdev, new_disk_conf)) {
1513                 retcode = ERR_NOMEM;
1514                 goto force_diskless_dec;
1515         }
1516
1517         /* Prevent shrinking of consistent devices ! */
1518         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1519             drbd_new_dev_size(mdev, nbc, nbc->disk_conf->disk_size, 0) < nbc->md.la_size_sect) {
1520                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1521                 retcode = ERR_DISK_TOO_SMALL;
1522                 goto force_diskless_dec;
1523         }
1524
1525         /* Reset the "barriers don't work" bits here, then force meta data to
1526          * be written, to ensure we determine if barriers are supported. */
1527         if (new_disk_conf->md_flushes)
1528                 clear_bit(MD_NO_FUA, &mdev->flags);
1529         else
1530                 set_bit(MD_NO_FUA, &mdev->flags);
1531
1532         /* Point of no return reached.
1533          * Devices and memory are no longer released by error cleanup below.
1534          * now mdev takes over responsibility, and the state engine should
1535          * clean it up somewhere.  */
1536         D_ASSERT(mdev->ldev == NULL);
1537         mdev->ldev = nbc;
1538         mdev->resync = resync_lru;
1539         mdev->rs_plan_s = new_plan;
1540         nbc = NULL;
1541         resync_lru = NULL;
1542         new_disk_conf = NULL;
1543         new_plan = NULL;
1544
1545         drbd_bump_write_ordering(mdev->tconn, WO_bdev_flush);
1546
1547         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1548                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1549         else
1550                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1551
1552         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1553             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod))
1554                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1555
1556         mdev->send_cnt = 0;
1557         mdev->recv_cnt = 0;
1558         mdev->read_cnt = 0;
1559         mdev->writ_cnt = 0;
1560
1561         drbd_reconsider_max_bio_size(mdev);
1562
1563         /* If I am currently not R_PRIMARY,
1564          * but meta data primary indicator is set,
1565          * I just now recover from a hard crash,
1566          * and have been R_PRIMARY before that crash.
1567          *
1568          * Now, if I had no connection before that crash
1569          * (have been degraded R_PRIMARY), chances are that
1570          * I won't find my peer now either.
1571          *
1572          * In that case, and _only_ in that case,
1573          * we use the degr-wfc-timeout instead of the default,
1574          * so we can automatically recover from a crash of a
1575          * degraded but active "cluster" after a certain timeout.
1576          */
1577         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1578         if (mdev->state.role != R_PRIMARY &&
1579              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1580             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1581                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1582
1583         dd = drbd_determine_dev_size(mdev, 0);
1584         if (dd == dev_size_error) {
1585                 retcode = ERR_NOMEM_BITMAP;
1586                 goto force_diskless_dec;
1587         } else if (dd == grew)
1588                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1589
1590         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC) ||
1591             (test_bit(CRASHED_PRIMARY, &mdev->flags) &&
1592              drbd_md_test_flag(mdev->ldev, MDF_AL_DISABLED))) {
1593                 dev_info(DEV, "Assuming that all blocks are out of sync "
1594                      "(aka FullSync)\n");
1595                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1596                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1597                         retcode = ERR_IO_MD_DISK;
1598                         goto force_diskless_dec;
1599                 }
1600         } else {
1601                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1602                         "read from attaching", BM_LOCKED_MASK)) {
1603                         retcode = ERR_IO_MD_DISK;
1604                         goto force_diskless_dec;
1605                 }
1606         }
1607
1608         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1609                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1610
1611         spin_lock_irq(&mdev->tconn->req_lock);
1612         os = drbd_read_state(mdev);
1613         ns = os;
1614         /* If MDF_CONSISTENT is not set go into inconsistent state,
1615            otherwise investigate MDF_WasUpToDate...
1616            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1617            otherwise into D_CONSISTENT state.
1618         */
1619         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1620                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1621                         ns.disk = D_CONSISTENT;
1622                 else
1623                         ns.disk = D_OUTDATED;
1624         } else {
1625                 ns.disk = D_INCONSISTENT;
1626         }
1627
1628         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1629                 ns.pdsk = D_OUTDATED;
1630
1631         rcu_read_lock();
1632         if (ns.disk == D_CONSISTENT &&
1633             (ns.pdsk == D_OUTDATED || rcu_dereference(mdev->ldev->disk_conf)->fencing == FP_DONT_CARE))
1634                 ns.disk = D_UP_TO_DATE;
1635
1636         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1637            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1638            this point, because drbd_request_state() modifies these
1639            flags. */
1640
1641         if (rcu_dereference(mdev->ldev->disk_conf)->al_updates)
1642                 mdev->ldev->md.flags &= ~MDF_AL_DISABLED;
1643         else
1644                 mdev->ldev->md.flags |= MDF_AL_DISABLED;
1645
1646         rcu_read_unlock();
1647
1648         /* In case we are C_CONNECTED postpone any decision on the new disk
1649            state after the negotiation phase. */
1650         if (mdev->state.conn == C_CONNECTED) {
1651                 mdev->new_state_tmp.i = ns.i;
1652                 ns.i = os.i;
1653                 ns.disk = D_NEGOTIATING;
1654
1655                 /* We expect to receive up-to-date UUIDs soon.
1656                    To avoid a race in receive_state, free p_uuid while
1657                    holding req_lock. I.e. atomic with the state change */
1658                 kfree(mdev->p_uuid);
1659                 mdev->p_uuid = NULL;
1660         }
1661
1662         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1663         spin_unlock_irq(&mdev->tconn->req_lock);
1664
1665         if (rv < SS_SUCCESS)
1666                 goto force_diskless_dec;
1667
1668         mod_timer(&mdev->request_timer, jiffies + HZ);
1669
1670         if (mdev->state.role == R_PRIMARY)
1671                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1672         else
1673                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1674
1675         drbd_md_mark_dirty(mdev);
1676         drbd_md_sync(mdev);
1677
1678         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1679         put_ldev(mdev);
1680         conn_reconfig_done(mdev->tconn);
1681         drbd_adm_finish(info, retcode);
1682         return 0;
1683
1684  force_diskless_dec:
1685         put_ldev(mdev);
1686  force_diskless:
1687         drbd_force_state(mdev, NS(disk, D_DISKLESS));
1688         drbd_md_sync(mdev);
1689  fail:
1690         conn_reconfig_done(mdev->tconn);
1691         if (nbc) {
1692                 if (nbc->backing_bdev)
1693                         blkdev_put(nbc->backing_bdev,
1694                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1695                 if (nbc->md_bdev)
1696                         blkdev_put(nbc->md_bdev,
1697                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1698                 kfree(nbc);
1699         }
1700         kfree(new_disk_conf);
1701         lc_destroy(resync_lru);
1702         kfree(new_plan);
1703
1704  finish:
1705         drbd_adm_finish(info, retcode);
1706         return 0;
1707 }
1708
1709 static int adm_detach(struct drbd_conf *mdev, int force)
1710 {
1711         enum drbd_state_rv retcode;
1712         int ret;
1713
1714         if (force) {
1715                 set_bit(FORCE_DETACH, &mdev->flags);
1716                 drbd_force_state(mdev, NS(disk, D_FAILED));
1717                 retcode = SS_SUCCESS;
1718                 goto out;
1719         }
1720
1721         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1722         drbd_md_get_buffer(mdev); /* make sure there is no in-flight meta-data IO */
1723         retcode = drbd_request_state(mdev, NS(disk, D_FAILED));
1724         drbd_md_put_buffer(mdev);
1725         /* D_FAILED will transition to DISKLESS. */
1726         ret = wait_event_interruptible(mdev->misc_wait,
1727                         mdev->state.disk != D_FAILED);
1728         drbd_resume_io(mdev);
1729         if ((int)retcode == (int)SS_IS_DISKLESS)
1730                 retcode = SS_NOTHING_TO_DO;
1731         if (ret)
1732                 retcode = ERR_INTR;
1733 out:
1734         return retcode;
1735 }
1736
1737 /* Detaching the disk is a process in multiple stages.  First we need to lock
1738  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1739  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1740  * internal references as well.
1741  * Only then we have finally detached. */
1742 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1743 {
1744         enum drbd_ret_code retcode;
1745         struct detach_parms parms = { };
1746         int err;
1747
1748         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1749         if (!adm_ctx.reply_skb)
1750                 return retcode;
1751         if (retcode != NO_ERROR)
1752                 goto out;
1753
1754         if (info->attrs[DRBD_NLA_DETACH_PARMS]) {
1755                 err = detach_parms_from_attrs(&parms, info);
1756                 if (err) {
1757                         retcode = ERR_MANDATORY_TAG;
1758                         drbd_msg_put_info(from_attrs_err_to_txt(err));
1759                         goto out;
1760                 }
1761         }
1762
1763         retcode = adm_detach(adm_ctx.mdev, parms.force_detach);
1764 out:
1765         drbd_adm_finish(info, retcode);
1766         return 0;
1767 }
1768
1769 static bool conn_resync_running(struct drbd_tconn *tconn)
1770 {
1771         struct drbd_conf *mdev;
1772         bool rv = false;
1773         int vnr;
1774
1775         rcu_read_lock();
1776         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1777                 if (mdev->state.conn == C_SYNC_SOURCE ||
1778                     mdev->state.conn == C_SYNC_TARGET ||
1779                     mdev->state.conn == C_PAUSED_SYNC_S ||
1780                     mdev->state.conn == C_PAUSED_SYNC_T) {
1781                         rv = true;
1782                         break;
1783                 }
1784         }
1785         rcu_read_unlock();
1786
1787         return rv;
1788 }
1789
1790 static bool conn_ov_running(struct drbd_tconn *tconn)
1791 {
1792         struct drbd_conf *mdev;
1793         bool rv = false;
1794         int vnr;
1795
1796         rcu_read_lock();
1797         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1798                 if (mdev->state.conn == C_VERIFY_S ||
1799                     mdev->state.conn == C_VERIFY_T) {
1800                         rv = true;
1801                         break;
1802                 }
1803         }
1804         rcu_read_unlock();
1805
1806         return rv;
1807 }
1808
1809 static enum drbd_ret_code
1810 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1811 {
1812         struct drbd_conf *mdev;
1813         int i;
1814
1815         if (old_conf && tconn->cstate == C_WF_REPORT_PARAMS && tconn->agreed_pro_version < 100) {
1816                 if (new_conf->wire_protocol != old_conf->wire_protocol)
1817                         return ERR_NEED_APV_100;
1818
1819                 if (new_conf->two_primaries != old_conf->two_primaries)
1820                         return ERR_NEED_APV_100;
1821
1822                 if (strcmp(new_conf->integrity_alg, old_conf->integrity_alg))
1823                         return ERR_NEED_APV_100;
1824         }
1825
1826         if (!new_conf->two_primaries &&
1827             conn_highest_role(tconn) == R_PRIMARY &&
1828             conn_highest_peer(tconn) == R_PRIMARY)
1829                 return ERR_NEED_ALLOW_TWO_PRI;
1830
1831         if (new_conf->two_primaries &&
1832             (new_conf->wire_protocol != DRBD_PROT_C))
1833                 return ERR_NOT_PROTO_C;
1834
1835         idr_for_each_entry(&tconn->volumes, mdev, i) {
1836                 if (get_ldev(mdev)) {
1837                         enum drbd_fencing_p fp = rcu_dereference(mdev->ldev->disk_conf)->fencing;
1838                         put_ldev(mdev);
1839                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1840                                 return ERR_STONITH_AND_PROT_A;
1841                 }
1842                 if (mdev->state.role == R_PRIMARY && new_conf->discard_my_data)
1843                         return ERR_DISCARD_IMPOSSIBLE;
1844         }
1845
1846         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1847                 return ERR_CONG_NOT_PROTO_A;
1848
1849         return NO_ERROR;
1850 }
1851
1852 static enum drbd_ret_code
1853 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1854 {
1855         static enum drbd_ret_code rv;
1856         struct drbd_conf *mdev;
1857         int i;
1858
1859         rcu_read_lock();
1860         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1861         rcu_read_unlock();
1862
1863         /* tconn->volumes protected by genl_lock() here */
1864         idr_for_each_entry(&tconn->volumes, mdev, i) {
1865                 if (!mdev->bitmap) {
1866                         if(drbd_bm_init(mdev))
1867                                 return ERR_NOMEM;
1868                 }
1869         }
1870
1871         return rv;
1872 }
1873
1874 struct crypto {
1875         struct crypto_hash *verify_tfm;
1876         struct crypto_hash *csums_tfm;
1877         struct crypto_hash *cram_hmac_tfm;
1878         struct crypto_hash *integrity_tfm;
1879 };
1880
1881 static int
1882 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1883 {
1884         if (!tfm_name[0])
1885                 return NO_ERROR;
1886
1887         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1888         if (IS_ERR(*tfm)) {
1889                 *tfm = NULL;
1890                 return err_alg;
1891         }
1892
1893         return NO_ERROR;
1894 }
1895
1896 static enum drbd_ret_code
1897 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1898 {
1899         char hmac_name[CRYPTO_MAX_ALG_NAME];
1900         enum drbd_ret_code rv;
1901
1902         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1903                        ERR_CSUMS_ALG);
1904         if (rv != NO_ERROR)
1905                 return rv;
1906         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1907                        ERR_VERIFY_ALG);
1908         if (rv != NO_ERROR)
1909                 return rv;
1910         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1911                        ERR_INTEGRITY_ALG);
1912         if (rv != NO_ERROR)
1913                 return rv;
1914         if (new_conf->cram_hmac_alg[0] != 0) {
1915                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1916                          new_conf->cram_hmac_alg);
1917
1918                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1919                                ERR_AUTH_ALG);
1920         }
1921
1922         return rv;
1923 }
1924
1925 static void free_crypto(struct crypto *crypto)
1926 {
1927         crypto_free_hash(crypto->cram_hmac_tfm);
1928         crypto_free_hash(crypto->integrity_tfm);
1929         crypto_free_hash(crypto->csums_tfm);
1930         crypto_free_hash(crypto->verify_tfm);
1931 }
1932
1933 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1934 {
1935         enum drbd_ret_code retcode;
1936         struct drbd_tconn *tconn;
1937         struct net_conf *old_conf, *new_conf = NULL;
1938         int err;
1939         int ovr; /* online verify running */
1940         int rsr; /* re-sync running */
1941         struct crypto crypto = { };
1942
1943         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
1944         if (!adm_ctx.reply_skb)
1945                 return retcode;
1946         if (retcode != NO_ERROR)
1947                 goto out;
1948
1949         tconn = adm_ctx.tconn;
1950
1951         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1952         if (!new_conf) {
1953                 retcode = ERR_NOMEM;
1954                 goto out;
1955         }
1956
1957         conn_reconfig_start(tconn);
1958
1959         mutex_lock(&tconn->data.mutex);
1960         mutex_lock(&tconn->conf_update);
1961         old_conf = tconn->net_conf;
1962
1963         if (!old_conf) {
1964                 drbd_msg_put_info("net conf missing, try connect");
1965                 retcode = ERR_INVALID_REQUEST;
1966                 goto fail;
1967         }
1968
1969         *new_conf = *old_conf;
1970         if (should_set_defaults(info))
1971                 set_net_conf_defaults(new_conf);
1972
1973         err = net_conf_from_attrs_for_change(new_conf, info);
1974         if (err && err != -ENOMSG) {
1975                 retcode = ERR_MANDATORY_TAG;
1976                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1977                 goto fail;
1978         }
1979
1980         retcode = check_net_options(tconn, new_conf);
1981         if (retcode != NO_ERROR)
1982                 goto fail;
1983
1984         /* re-sync running */
1985         rsr = conn_resync_running(tconn);
1986         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1987                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1988                 goto fail;
1989         }
1990
1991         /* online verify running */
1992         ovr = conn_ov_running(tconn);
1993         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1994                 retcode = ERR_VERIFY_RUNNING;
1995                 goto fail;
1996         }
1997
1998         retcode = alloc_crypto(&crypto, new_conf);
1999         if (retcode != NO_ERROR)
2000                 goto fail;
2001
2002         rcu_assign_pointer(tconn->net_conf, new_conf);
2003
2004         if (!rsr) {
2005                 crypto_free_hash(tconn->csums_tfm);
2006                 tconn->csums_tfm = crypto.csums_tfm;
2007                 crypto.csums_tfm = NULL;
2008         }
2009         if (!ovr) {
2010                 crypto_free_hash(tconn->verify_tfm);
2011                 tconn->verify_tfm = crypto.verify_tfm;
2012                 crypto.verify_tfm = NULL;
2013         }
2014
2015         crypto_free_hash(tconn->integrity_tfm);
2016         tconn->integrity_tfm = crypto.integrity_tfm;
2017         if (tconn->cstate >= C_WF_REPORT_PARAMS && tconn->agreed_pro_version >= 100)
2018                 /* Do this without trying to take tconn->data.mutex again.  */
2019                 __drbd_send_protocol(tconn, P_PROTOCOL_UPDATE);
2020
2021         crypto_free_hash(tconn->cram_hmac_tfm);
2022         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2023
2024         mutex_unlock(&tconn->conf_update);
2025         mutex_unlock(&tconn->data.mutex);
2026         synchronize_rcu();
2027         kfree(old_conf);
2028
2029         if (tconn->cstate >= C_WF_REPORT_PARAMS)
2030                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
2031
2032         goto done;
2033
2034  fail:
2035         mutex_unlock(&tconn->conf_update);
2036         mutex_unlock(&tconn->data.mutex);
2037         free_crypto(&crypto);
2038         kfree(new_conf);
2039  done:
2040         conn_reconfig_done(tconn);
2041  out:
2042         drbd_adm_finish(info, retcode);
2043         return 0;
2044 }
2045
2046 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
2047 {
2048         struct drbd_conf *mdev;
2049         struct net_conf *old_conf, *new_conf = NULL;
2050         struct crypto crypto = { };
2051         struct drbd_tconn *tconn;
2052         enum drbd_ret_code retcode;
2053         int i;
2054         int err;
2055
2056         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2057
2058         if (!adm_ctx.reply_skb)
2059                 return retcode;
2060         if (retcode != NO_ERROR)
2061                 goto out;
2062         if (!(adm_ctx.my_addr && adm_ctx.peer_addr)) {
2063                 drbd_msg_put_info("connection endpoint(s) missing");
2064                 retcode = ERR_INVALID_REQUEST;
2065                 goto out;
2066         }
2067
2068         /* No need for _rcu here. All reconfiguration is
2069          * strictly serialized on genl_lock(). We are protected against
2070          * concurrent reconfiguration/addition/deletion */
2071         list_for_each_entry(tconn, &drbd_tconns, all_tconn) {
2072                 if (nla_len(adm_ctx.my_addr) == tconn->my_addr_len &&
2073                     !memcmp(nla_data(adm_ctx.my_addr), &tconn->my_addr, tconn->my_addr_len)) {
2074                         retcode = ERR_LOCAL_ADDR;
2075                         goto out;
2076                 }
2077
2078                 if (nla_len(adm_ctx.peer_addr) == tconn->peer_addr_len &&
2079                     !memcmp(nla_data(adm_ctx.peer_addr), &tconn->peer_addr, tconn->peer_addr_len)) {
2080                         retcode = ERR_PEER_ADDR;
2081                         goto out;
2082                 }
2083         }
2084
2085         tconn = adm_ctx.tconn;
2086         conn_reconfig_start(tconn);
2087
2088         if (tconn->cstate > C_STANDALONE) {
2089                 retcode = ERR_NET_CONFIGURED;
2090                 goto fail;
2091         }
2092
2093         /* allocation not in the IO path, drbdsetup / netlink process context */
2094         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2095         if (!new_conf) {
2096                 retcode = ERR_NOMEM;
2097                 goto fail;
2098         }
2099
2100         set_net_conf_defaults(new_conf);
2101
2102         err = net_conf_from_attrs(new_conf, info);
2103         if (err && err != -ENOMSG) {
2104                 retcode = ERR_MANDATORY_TAG;
2105                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2106                 goto fail;
2107         }
2108
2109         retcode = check_net_options(tconn, new_conf);
2110         if (retcode != NO_ERROR)
2111                 goto fail;
2112
2113         retcode = alloc_crypto(&crypto, new_conf);
2114         if (retcode != NO_ERROR)
2115                 goto fail;
2116
2117         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2118
2119         conn_flush_workqueue(tconn);
2120
2121         mutex_lock(&tconn->conf_update);
2122         old_conf = tconn->net_conf;
2123         if (old_conf) {
2124                 retcode = ERR_NET_CONFIGURED;
2125                 mutex_unlock(&tconn->conf_update);
2126                 goto fail;
2127         }
2128         rcu_assign_pointer(tconn->net_conf, new_conf);
2129
2130         conn_free_crypto(tconn);
2131         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2132         tconn->integrity_tfm = crypto.integrity_tfm;
2133         tconn->csums_tfm = crypto.csums_tfm;
2134         tconn->verify_tfm = crypto.verify_tfm;
2135
2136         tconn->my_addr_len = nla_len(adm_ctx.my_addr);
2137         memcpy(&tconn->my_addr, nla_data(adm_ctx.my_addr), tconn->my_addr_len);
2138         tconn->peer_addr_len = nla_len(adm_ctx.peer_addr);
2139         memcpy(&tconn->peer_addr, nla_data(adm_ctx.peer_addr), tconn->peer_addr_len);
2140
2141         mutex_unlock(&tconn->conf_update);
2142
2143         rcu_read_lock();
2144         idr_for_each_entry(&tconn->volumes, mdev, i) {
2145                 mdev->send_cnt = 0;
2146                 mdev->recv_cnt = 0;
2147         }
2148         rcu_read_unlock();
2149
2150         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2151
2152         conn_reconfig_done(tconn);
2153         drbd_adm_finish(info, retcode);
2154         return 0;
2155
2156 fail:
2157         free_crypto(&crypto);
2158         kfree(new_conf);
2159
2160         conn_reconfig_done(tconn);
2161 out:
2162         drbd_adm_finish(info, retcode);
2163         return 0;
2164 }
2165
2166 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2167 {
2168         enum drbd_state_rv rv;
2169
2170         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2171                         force ? CS_HARD : 0);
2172
2173         switch (rv) {
2174         case SS_NOTHING_TO_DO:
2175                 break;
2176         case SS_ALREADY_STANDALONE:
2177                 return SS_SUCCESS;
2178         case SS_PRIMARY_NOP:
2179                 /* Our state checking code wants to see the peer outdated. */
2180                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2181                                                 pdsk, D_OUTDATED), CS_VERBOSE);
2182                 break;
2183         case SS_CW_FAILED_BY_PEER:
2184                 /* The peer probably wants to see us outdated. */
2185                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2186                                                         disk, D_OUTDATED), 0);
2187                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2188                         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2189                                         CS_HARD);
2190                 }
2191                 break;
2192         default:;
2193                 /* no special handling necessary */
2194         }
2195
2196         if (rv >= SS_SUCCESS) {
2197                 enum drbd_state_rv rv2;
2198                 /* No one else can reconfigure the network while I am here.
2199                  * The state handling only uses drbd_thread_stop_nowait(),
2200                  * we want to really wait here until the receiver is no more.
2201                  */
2202                 drbd_thread_stop(&adm_ctx.tconn->receiver);
2203
2204                 /* Race breaker.  This additional state change request may be
2205                  * necessary, if this was a forced disconnect during a receiver
2206                  * restart.  We may have "killed" the receiver thread just
2207                  * after drbdd_init() returned.  Typically, we should be
2208                  * C_STANDALONE already, now, and this becomes a no-op.
2209                  */
2210                 rv2 = conn_request_state(tconn, NS(conn, C_STANDALONE),
2211                                 CS_VERBOSE | CS_HARD);
2212                 if (rv2 < SS_SUCCESS)
2213                         conn_err(tconn,
2214                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2215                                 rv2);
2216         }
2217         return rv;
2218 }
2219
2220 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2221 {
2222         struct disconnect_parms parms;
2223         struct drbd_tconn *tconn;
2224         enum drbd_state_rv rv;
2225         enum drbd_ret_code retcode;
2226         int err;
2227
2228         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
2229         if (!adm_ctx.reply_skb)
2230                 return retcode;
2231         if (retcode != NO_ERROR)
2232                 goto fail;
2233
2234         tconn = adm_ctx.tconn;
2235         memset(&parms, 0, sizeof(parms));
2236         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2237                 err = disconnect_parms_from_attrs(&parms, info);
2238                 if (err) {
2239                         retcode = ERR_MANDATORY_TAG;
2240                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2241                         goto fail;
2242                 }
2243         }
2244
2245         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2246         if (rv < SS_SUCCESS)
2247                 retcode = rv;  /* FIXME: Type mismatch. */
2248         else
2249                 retcode = NO_ERROR;
2250  fail:
2251         drbd_adm_finish(info, retcode);
2252         return 0;
2253 }
2254
2255 void resync_after_online_grow(struct drbd_conf *mdev)
2256 {
2257         int iass; /* I am sync source */
2258
2259         dev_info(DEV, "Resync of new storage after online grow\n");
2260         if (mdev->state.role != mdev->state.peer)
2261                 iass = (mdev->state.role == R_PRIMARY);
2262         else
2263                 iass = test_bit(RESOLVE_CONFLICTS, &mdev->tconn->flags);
2264
2265         if (iass)
2266                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2267         else
2268                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2269 }
2270
2271 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2272 {
2273         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2274         struct resize_parms rs;
2275         struct drbd_conf *mdev;
2276         enum drbd_ret_code retcode;
2277         enum determine_dev_size dd;
2278         enum dds_flags ddsf;
2279         sector_t u_size;
2280         int err;
2281
2282         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2283         if (!adm_ctx.reply_skb)
2284                 return retcode;
2285         if (retcode != NO_ERROR)
2286                 goto fail;
2287
2288         memset(&rs, 0, sizeof(struct resize_parms));
2289         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2290                 err = resize_parms_from_attrs(&rs, info);
2291                 if (err) {
2292                         retcode = ERR_MANDATORY_TAG;
2293                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2294                         goto fail;
2295                 }
2296         }
2297
2298         mdev = adm_ctx.mdev;
2299         if (mdev->state.conn > C_CONNECTED) {
2300                 retcode = ERR_RESIZE_RESYNC;
2301                 goto fail;
2302         }
2303
2304         if (mdev->state.role == R_SECONDARY &&
2305             mdev->state.peer == R_SECONDARY) {
2306                 retcode = ERR_NO_PRIMARY;
2307                 goto fail;
2308         }
2309
2310         if (!get_ldev(mdev)) {
2311                 retcode = ERR_NO_DISK;
2312                 goto fail;
2313         }
2314
2315         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2316                 retcode = ERR_NEED_APV_93;
2317                 goto fail_ldev;
2318         }
2319
2320         rcu_read_lock();
2321         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
2322         rcu_read_unlock();
2323         if (u_size != (sector_t)rs.resize_size) {
2324                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2325                 if (!new_disk_conf) {
2326                         retcode = ERR_NOMEM;
2327                         goto fail_ldev;
2328                 }
2329         }
2330
2331         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2332                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2333
2334         if (new_disk_conf) {
2335                 mutex_lock(&mdev->tconn->conf_update);
2336                 old_disk_conf = mdev->ldev->disk_conf;
2337                 *new_disk_conf = *old_disk_conf;
2338                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2339                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
2340                 mutex_unlock(&mdev->tconn->conf_update);
2341                 synchronize_rcu();
2342                 kfree(old_disk_conf);
2343         }
2344
2345         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2346         dd = drbd_determine_dev_size(mdev, ddsf);
2347         drbd_md_sync(mdev);
2348         put_ldev(mdev);
2349         if (dd == dev_size_error) {
2350                 retcode = ERR_NOMEM_BITMAP;
2351                 goto fail;
2352         }
2353
2354         if (mdev->state.conn == C_CONNECTED) {
2355                 if (dd == grew)
2356                         set_bit(RESIZE_PENDING, &mdev->flags);
2357
2358                 drbd_send_uuids(mdev);
2359                 drbd_send_sizes(mdev, 1, ddsf);
2360         }
2361
2362  fail:
2363         drbd_adm_finish(info, retcode);
2364         return 0;
2365
2366  fail_ldev:
2367         put_ldev(mdev);
2368         goto fail;
2369 }
2370
2371 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2372 {
2373         enum drbd_ret_code retcode;
2374         struct drbd_tconn *tconn;
2375         struct res_opts res_opts;
2376         int err;
2377
2378         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2379         if (!adm_ctx.reply_skb)
2380                 return retcode;
2381         if (retcode != NO_ERROR)
2382                 goto fail;
2383         tconn = adm_ctx.tconn;
2384
2385         res_opts = tconn->res_opts;
2386         if (should_set_defaults(info))
2387                 set_res_opts_defaults(&res_opts);
2388
2389         err = res_opts_from_attrs(&res_opts, info);
2390         if (err && err != -ENOMSG) {
2391                 retcode = ERR_MANDATORY_TAG;
2392                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2393                 goto fail;
2394         }
2395
2396         err = set_resource_options(tconn, &res_opts);
2397         if (err) {
2398                 retcode = ERR_INVALID_REQUEST;
2399                 if (err == -ENOMEM)
2400                         retcode = ERR_NOMEM;
2401         }
2402
2403 fail:
2404         drbd_adm_finish(info, retcode);
2405         return 0;
2406 }
2407
2408 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2409 {
2410         struct drbd_conf *mdev;
2411         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2412
2413         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2414         if (!adm_ctx.reply_skb)
2415                 return retcode;
2416         if (retcode != NO_ERROR)
2417                 goto out;
2418
2419         mdev = adm_ctx.mdev;
2420
2421         /* If there is still bitmap IO pending, probably because of a previous
2422          * resync just being finished, wait for it before requesting a new resync.
2423          * Also wait for it's after_state_ch(). */
2424         drbd_suspend_io(mdev);
2425         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2426         drbd_flush_workqueue(mdev);
2427
2428         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2429
2430         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2431                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2432
2433         while (retcode == SS_NEED_CONNECTION) {
2434                 spin_lock_irq(&mdev->tconn->req_lock);
2435                 if (mdev->state.conn < C_CONNECTED)
2436                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2437                 spin_unlock_irq(&mdev->tconn->req_lock);
2438
2439                 if (retcode != SS_NEED_CONNECTION)
2440                         break;
2441
2442                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2443         }
2444         drbd_resume_io(mdev);
2445
2446 out:
2447         drbd_adm_finish(info, retcode);
2448         return 0;
2449 }
2450
2451 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2452                 union drbd_state mask, union drbd_state val)
2453 {
2454         enum drbd_ret_code retcode;
2455
2456         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2457         if (!adm_ctx.reply_skb)
2458                 return retcode;
2459         if (retcode != NO_ERROR)
2460                 goto out;
2461
2462         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2463 out:
2464         drbd_adm_finish(info, retcode);
2465         return 0;
2466 }
2467
2468 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2469 {
2470         int rv;
2471
2472         rv = drbd_bmio_set_n_write(mdev);
2473         drbd_suspend_al(mdev);
2474         return rv;
2475 }
2476
2477 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2478 {
2479         int retcode; /* drbd_ret_code, drbd_state_rv */
2480         struct drbd_conf *mdev;
2481
2482         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2483         if (!adm_ctx.reply_skb)
2484                 return retcode;
2485         if (retcode != NO_ERROR)
2486                 goto out;
2487
2488         mdev = adm_ctx.mdev;
2489
2490         /* If there is still bitmap IO pending, probably because of a previous
2491          * resync just being finished, wait for it before requesting a new resync.
2492          * Also wait for it's after_state_ch(). */
2493         drbd_suspend_io(mdev);
2494         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2495         drbd_flush_workqueue(mdev);
2496
2497         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S), CS_ORDERED);
2498         if (retcode < SS_SUCCESS) {
2499                 if (retcode == SS_NEED_CONNECTION && mdev->state.role == R_PRIMARY) {
2500                         /* The peer will get a resync upon connect anyways.
2501                          * Just make that into a full resync. */
2502                         retcode = drbd_request_state(mdev, NS(pdsk, D_INCONSISTENT));
2503                         if (retcode >= SS_SUCCESS) {
2504                                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_susp_al,
2505                                                    "set_n_write from invalidate_peer",
2506                                                    BM_LOCKED_SET_ALLOWED))
2507                                         retcode = ERR_IO_MD_DISK;
2508                         }
2509                 } else
2510                         retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S));
2511         }
2512         drbd_resume_io(mdev);
2513
2514 out:
2515         drbd_adm_finish(info, retcode);
2516         return 0;
2517 }
2518
2519 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2520 {
2521         enum drbd_ret_code retcode;
2522
2523         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2524         if (!adm_ctx.reply_skb)
2525                 return retcode;
2526         if (retcode != NO_ERROR)
2527                 goto out;
2528
2529         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2530                 retcode = ERR_PAUSE_IS_SET;
2531 out:
2532         drbd_adm_finish(info, retcode);
2533         return 0;
2534 }
2535
2536 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2537 {
2538         union drbd_dev_state s;
2539         enum drbd_ret_code retcode;
2540
2541         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2542         if (!adm_ctx.reply_skb)
2543                 return retcode;
2544         if (retcode != NO_ERROR)
2545                 goto out;
2546
2547         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2548                 s = adm_ctx.mdev->state;
2549                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2550                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2551                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2552                 } else {
2553                         retcode = ERR_PAUSE_IS_CLEAR;
2554                 }
2555         }
2556
2557 out:
2558         drbd_adm_finish(info, retcode);
2559         return 0;
2560 }
2561
2562 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2563 {
2564         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2565 }
2566
2567 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2568 {
2569         struct drbd_conf *mdev;
2570         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2571
2572         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2573         if (!adm_ctx.reply_skb)
2574                 return retcode;
2575         if (retcode != NO_ERROR)
2576                 goto out;
2577
2578         mdev = adm_ctx.mdev;
2579         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2580                 drbd_uuid_new_current(mdev);
2581                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2582         }
2583         drbd_suspend_io(mdev);
2584         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2585         if (retcode == SS_SUCCESS) {
2586                 if (mdev->state.conn < C_CONNECTED)
2587                         tl_clear(mdev->tconn);
2588                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2589                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2590         }
2591         drbd_resume_io(mdev);
2592
2593 out:
2594         drbd_adm_finish(info, retcode);
2595         return 0;
2596 }
2597
2598 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2599 {
2600         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2601 }
2602
2603 int nla_put_drbd_cfg_context(struct sk_buff *skb, struct drbd_tconn *tconn, unsigned vnr)
2604 {
2605         struct nlattr *nla;
2606         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2607         if (!nla)
2608                 goto nla_put_failure;
2609         if (vnr != VOLUME_UNSPECIFIED &&
2610             nla_put_u32(skb, T_ctx_volume, vnr))
2611                 goto nla_put_failure;
2612         if (nla_put_string(skb, T_ctx_resource_name, tconn->name))
2613                 goto nla_put_failure;
2614         if (tconn->my_addr_len &&
2615             nla_put(skb, T_ctx_my_addr, tconn->my_addr_len, &tconn->my_addr))
2616                 goto nla_put_failure;
2617         if (tconn->peer_addr_len &&
2618             nla_put(skb, T_ctx_peer_addr, tconn->peer_addr_len, &tconn->peer_addr))
2619                 goto nla_put_failure;
2620         nla_nest_end(skb, nla);
2621         return 0;
2622
2623 nla_put_failure:
2624         if (nla)
2625                 nla_nest_cancel(skb, nla);
2626         return -EMSGSIZE;
2627 }
2628
2629 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2630                 const struct sib_info *sib)
2631 {
2632         struct state_info *si = NULL; /* for sizeof(si->member); */
2633         struct net_conf *nc;
2634         struct nlattr *nla;
2635         int got_ldev;
2636         int err = 0;
2637         int exclude_sensitive;
2638
2639         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2640          * to.  So we better exclude_sensitive information.
2641          *
2642          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2643          * in the context of the requesting user process. Exclude sensitive
2644          * information, unless current has superuser.
2645          *
2646          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2647          * relies on the current implementation of netlink_dump(), which
2648          * executes the dump callback successively from netlink_recvmsg(),
2649          * always in the context of the receiving process */
2650         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2651
2652         got_ldev = get_ldev(mdev);
2653
2654         /* We need to add connection name and volume number information still.
2655          * Minor number is in drbd_genlmsghdr. */
2656         if (nla_put_drbd_cfg_context(skb, mdev->tconn, mdev->vnr))
2657                 goto nla_put_failure;
2658
2659         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2660                 goto nla_put_failure;
2661
2662         rcu_read_lock();
2663         if (got_ldev)
2664                 if (disk_conf_to_skb(skb, rcu_dereference(mdev->ldev->disk_conf), exclude_sensitive))
2665                         goto nla_put_failure;
2666
2667         nc = rcu_dereference(mdev->tconn->net_conf);
2668         if (nc)
2669                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2670         rcu_read_unlock();
2671         if (err)
2672                 goto nla_put_failure;
2673
2674         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2675         if (!nla)
2676                 goto nla_put_failure;
2677         if (nla_put_u32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY) ||
2678             nla_put_u32(skb, T_current_state, mdev->state.i) ||
2679             nla_put_u64(skb, T_ed_uuid, mdev->ed_uuid) ||
2680             nla_put_u64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev)) ||
2681             nla_put_u64(skb, T_send_cnt, mdev->send_cnt) ||
2682             nla_put_u64(skb, T_recv_cnt, mdev->recv_cnt) ||
2683             nla_put_u64(skb, T_read_cnt, mdev->read_cnt) ||
2684             nla_put_u64(skb, T_writ_cnt, mdev->writ_cnt) ||
2685             nla_put_u64(skb, T_al_writ_cnt, mdev->al_writ_cnt) ||
2686             nla_put_u64(skb, T_bm_writ_cnt, mdev->bm_writ_cnt) ||
2687             nla_put_u32(skb, T_ap_bio_cnt, atomic_read(&mdev->ap_bio_cnt)) ||
2688             nla_put_u32(skb, T_ap_pending_cnt, atomic_read(&mdev->ap_pending_cnt)) ||
2689             nla_put_u32(skb, T_rs_pending_cnt, atomic_read(&mdev->rs_pending_cnt)))
2690                 goto nla_put_failure;
2691
2692         if (got_ldev) {
2693                 int err;
2694
2695                 spin_lock_irq(&mdev->ldev->md.uuid_lock);
2696                 err = nla_put(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2697                 spin_unlock_irq(&mdev->ldev->md.uuid_lock);
2698
2699                 if (err)
2700                         goto nla_put_failure;
2701
2702                 if (nla_put_u32(skb, T_disk_flags, mdev->ldev->md.flags) ||
2703                     nla_put_u64(skb, T_bits_total, drbd_bm_bits(mdev)) ||
2704                     nla_put_u64(skb, T_bits_oos, drbd_bm_total_weight(mdev)))
2705                         goto nla_put_failure;
2706                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2707                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2708                         if (nla_put_u64(skb, T_bits_rs_total, mdev->rs_total) ||
2709                             nla_put_u64(skb, T_bits_rs_failed, mdev->rs_failed))
2710                                 goto nla_put_failure;
2711                 }
2712         }
2713
2714         if (sib) {
2715                 switch(sib->sib_reason) {
2716                 case SIB_SYNC_PROGRESS:
2717                 case SIB_GET_STATUS_REPLY:
2718                         break;
2719                 case SIB_STATE_CHANGE:
2720                         if (nla_put_u32(skb, T_prev_state, sib->os.i) ||
2721                             nla_put_u32(skb, T_new_state, sib->ns.i))
2722                                 goto nla_put_failure;
2723                         break;
2724                 case SIB_HELPER_POST:
2725                         if (nla_put_u32(skb, T_helper_exit_code,
2726                                         sib->helper_exit_code))
2727                                 goto nla_put_failure;
2728                         /* fall through */
2729                 case SIB_HELPER_PRE:
2730                         if (nla_put_string(skb, T_helper, sib->helper_name))
2731                                 goto nla_put_failure;
2732                         break;
2733                 }
2734         }
2735         nla_nest_end(skb, nla);
2736
2737         if (0)
2738 nla_put_failure:
2739                 err = -EMSGSIZE;
2740         if (got_ldev)
2741                 put_ldev(mdev);
2742         return err;
2743 }
2744
2745 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2746 {
2747         enum drbd_ret_code retcode;
2748         int err;
2749
2750         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2751         if (!adm_ctx.reply_skb)
2752                 return retcode;
2753         if (retcode != NO_ERROR)
2754                 goto out;
2755
2756         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2757         if (err) {
2758                 nlmsg_free(adm_ctx.reply_skb);
2759                 return err;
2760         }
2761 out:
2762         drbd_adm_finish(info, retcode);
2763         return 0;
2764 }
2765
2766 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2767 {
2768         struct drbd_conf *mdev;
2769         struct drbd_genlmsghdr *dh;
2770         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2771         struct drbd_tconn *tconn = NULL;
2772         struct drbd_tconn *tmp;
2773         unsigned volume = cb->args[1];
2774
2775         /* Open coded, deferred, iteration:
2776          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2777          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2778          *        ...
2779          *      }
2780          * }
2781          * where tconn is cb->args[0];
2782          * and i is cb->args[1];
2783          *
2784          * cb->args[2] indicates if we shall loop over all resources,
2785          * or just dump all volumes of a single resource.
2786          *
2787          * This may miss entries inserted after this dump started,
2788          * or entries deleted before they are reached.
2789          *
2790          * We need to make sure the mdev won't disappear while
2791          * we are looking at it, and revalidate our iterators
2792          * on each iteration.
2793          */
2794
2795         /* synchronize with conn_create()/conn_destroy() */
2796         rcu_read_lock();
2797         /* revalidate iterator position */
2798         list_for_each_entry_rcu(tmp, &drbd_tconns, all_tconn) {
2799                 if (pos == NULL) {
2800                         /* first iteration */
2801                         pos = tmp;
2802                         tconn = pos;
2803                         break;
2804                 }
2805                 if (tmp == pos) {
2806                         tconn = pos;
2807                         break;
2808                 }
2809         }
2810         if (tconn) {
2811 next_tconn:
2812                 mdev = idr_get_next(&tconn->volumes, &volume);
2813                 if (!mdev) {
2814                         /* No more volumes to dump on this tconn.
2815                          * Advance tconn iterator. */
2816                         pos = list_entry_rcu(tconn->all_tconn.next,
2817                                              struct drbd_tconn, all_tconn);
2818                         /* Did we dump any volume on this tconn yet? */
2819                         if (volume != 0) {
2820                                 /* If we reached the end of the list,
2821                                  * or only a single resource dump was requested,
2822                                  * we are done. */
2823                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2824                                         goto out;
2825                                 volume = 0;
2826                                 tconn = pos;
2827                                 goto next_tconn;
2828                         }
2829                 }
2830
2831                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
2832                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2833                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2834                 if (!dh)
2835                         goto out;
2836
2837                 if (!mdev) {
2838                         /* This is a tconn without a single volume.
2839                          * Suprisingly enough, it may have a network
2840                          * configuration. */
2841                         struct net_conf *nc;
2842                         dh->minor = -1U;
2843                         dh->ret_code = NO_ERROR;
2844                         if (nla_put_drbd_cfg_context(skb, tconn, VOLUME_UNSPECIFIED))
2845                                 goto cancel;
2846                         nc = rcu_dereference(tconn->net_conf);
2847                         if (nc && net_conf_to_skb(skb, nc, 1) != 0)
2848                                 goto cancel;
2849                         goto done;
2850                 }
2851
2852                 D_ASSERT(mdev->vnr == volume);
2853                 D_ASSERT(mdev->tconn == tconn);
2854
2855                 dh->minor = mdev_to_minor(mdev);
2856                 dh->ret_code = NO_ERROR;
2857
2858                 if (nla_put_status_info(skb, mdev, NULL)) {
2859 cancel:
2860                         genlmsg_cancel(skb, dh);
2861                         goto out;
2862                 }
2863 done:
2864                 genlmsg_end(skb, dh);
2865         }
2866
2867 out:
2868         rcu_read_unlock();
2869         /* where to start the next iteration */
2870         cb->args[0] = (long)pos;
2871         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2872
2873         /* No more tconns/volumes/minors found results in an empty skb.
2874          * Which will terminate the dump. */
2875         return skb->len;
2876 }
2877
2878 /*
2879  * Request status of all resources, or of all volumes within a single resource.
2880  *
2881  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2882  * Which means we cannot use the family->attrbuf or other such members, because
2883  * dump is NOT protected by the genl_lock().  During dump, we only have access
2884  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2885  *
2886  * Once things are setup properly, we call into get_one_status().
2887  */
2888 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2889 {
2890         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2891         struct nlattr *nla;
2892         const char *resource_name;
2893         struct drbd_tconn *tconn;
2894         int maxtype;
2895
2896         /* Is this a followup call? */
2897         if (cb->args[0]) {
2898                 /* ... of a single resource dump,
2899                  * and the resource iterator has been advanced already? */
2900                 if (cb->args[2] && cb->args[2] != cb->args[0])
2901                         return 0; /* DONE. */
2902                 goto dump;
2903         }
2904
2905         /* First call (from netlink_dump_start).  We need to figure out
2906          * which resource(s) the user wants us to dump. */
2907         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2908                         nlmsg_attrlen(cb->nlh, hdrlen),
2909                         DRBD_NLA_CFG_CONTEXT);
2910
2911         /* No explicit context given.  Dump all. */
2912         if (!nla)
2913                 goto dump;
2914         maxtype = ARRAY_SIZE(drbd_cfg_context_nl_policy) - 1;
2915         nla = drbd_nla_find_nested(maxtype, nla, __nla_type(T_ctx_resource_name));
2916         if (IS_ERR(nla))
2917                 return PTR_ERR(nla);
2918         /* context given, but no name present? */
2919         if (!nla)
2920                 return -EINVAL;
2921         resource_name = nla_data(nla);
2922         tconn = conn_get_by_name(resource_name);
2923
2924         if (!tconn)
2925                 return -ENODEV;
2926
2927         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2928
2929         /* prime iterators, and set "filter" mode mark:
2930          * only dump this tconn. */
2931         cb->args[0] = (long)tconn;
2932         /* cb->args[1] = 0; passed in this way. */
2933         cb->args[2] = (long)tconn;
2934
2935 dump:
2936         return get_one_status(skb, cb);
2937 }
2938
2939 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2940 {
2941         enum drbd_ret_code retcode;
2942         struct timeout_parms tp;
2943         int err;
2944
2945         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2946         if (!adm_ctx.reply_skb)
2947                 return retcode;
2948         if (retcode != NO_ERROR)
2949                 goto out;
2950
2951         tp.timeout_type =
2952                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2953                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2954                 UT_DEFAULT;
2955
2956         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2957         if (err) {
2958                 nlmsg_free(adm_ctx.reply_skb);
2959                 return err;
2960         }
2961 out:
2962         drbd_adm_finish(info, retcode);
2963         return 0;
2964 }
2965
2966 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2967 {
2968         struct drbd_conf *mdev;
2969         enum drbd_ret_code retcode;
2970         struct start_ov_parms parms;
2971
2972         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2973         if (!adm_ctx.reply_skb)
2974                 return retcode;
2975         if (retcode != NO_ERROR)
2976                 goto out;
2977
2978         mdev = adm_ctx.mdev;
2979
2980         /* resume from last known position, if possible */
2981         parms.ov_start_sector = mdev->ov_start_sector;
2982         parms.ov_stop_sector = ULLONG_MAX;
2983         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2984                 int err = start_ov_parms_from_attrs(&parms, info);
2985                 if (err) {
2986                         retcode = ERR_MANDATORY_TAG;
2987                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2988                         goto out;
2989                 }
2990         }
2991         /* w_make_ov_request expects position to be aligned */
2992         mdev->ov_start_sector = parms.ov_start_sector & ~(BM_SECT_PER_BIT-1);
2993         mdev->ov_stop_sector = parms.ov_stop_sector;
2994
2995         /* If there is still bitmap IO pending, e.g. previous resync or verify
2996          * just being finished, wait for it before requesting a new resync. */
2997         drbd_suspend_io(mdev);
2998         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2999         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
3000         drbd_resume_io(mdev);
3001 out:
3002         drbd_adm_finish(info, retcode);
3003         return 0;
3004 }
3005
3006
3007 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
3008 {
3009         struct drbd_conf *mdev;
3010         enum drbd_ret_code retcode;
3011         int skip_initial_sync = 0;
3012         int err;
3013         struct new_c_uuid_parms args;
3014
3015         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3016         if (!adm_ctx.reply_skb)
3017                 return retcode;
3018         if (retcode != NO_ERROR)
3019                 goto out_nolock;
3020
3021         mdev = adm_ctx.mdev;
3022         memset(&args, 0, sizeof(args));
3023         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
3024                 err = new_c_uuid_parms_from_attrs(&args, info);
3025                 if (err) {
3026                         retcode = ERR_MANDATORY_TAG;
3027                         drbd_msg_put_info(from_attrs_err_to_txt(err));
3028                         goto out_nolock;
3029                 }
3030         }
3031
3032         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
3033
3034         if (!get_ldev(mdev)) {
3035                 retcode = ERR_NO_DISK;
3036                 goto out;
3037         }
3038
3039         /* this is "skip initial sync", assume to be clean */
3040         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
3041             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
3042                 dev_info(DEV, "Preparing to skip initial sync\n");
3043                 skip_initial_sync = 1;
3044         } else if (mdev->state.conn != C_STANDALONE) {
3045                 retcode = ERR_CONNECTED;
3046                 goto out_dec;
3047         }
3048
3049         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
3050         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
3051
3052         if (args.clear_bm) {
3053                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
3054                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
3055                 if (err) {
3056                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
3057                         retcode = ERR_IO_MD_DISK;
3058                 }
3059                 if (skip_initial_sync) {
3060                         drbd_send_uuids_skip_initial_sync(mdev);
3061                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
3062                         drbd_print_uuids(mdev, "cleared bitmap UUID");
3063                         spin_lock_irq(&mdev->tconn->req_lock);
3064                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
3065                                         CS_VERBOSE, NULL);
3066                         spin_unlock_irq(&mdev->tconn->req_lock);
3067                 }
3068         }
3069
3070         drbd_md_sync(mdev);
3071 out_dec:
3072         put_ldev(mdev);
3073 out:
3074         mutex_unlock(mdev->state_mutex);
3075 out_nolock:
3076         drbd_adm_finish(info, retcode);
3077         return 0;
3078 }
3079
3080 static enum drbd_ret_code
3081 drbd_check_resource_name(const char *name)
3082 {
3083         if (!name || !name[0]) {
3084                 drbd_msg_put_info("resource name missing");
3085                 return ERR_MANDATORY_TAG;
3086         }
3087         /* if we want to use these in sysfs/configfs/debugfs some day,
3088          * we must not allow slashes */
3089         if (strchr(name, '/')) {
3090                 drbd_msg_put_info("invalid resource name");
3091                 return ERR_INVALID_REQUEST;
3092         }
3093         return NO_ERROR;
3094 }
3095
3096 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info)
3097 {
3098         enum drbd_ret_code retcode;
3099         struct res_opts res_opts;
3100         int err;
3101
3102         retcode = drbd_adm_prepare(skb, info, 0);
3103         if (!adm_ctx.reply_skb)
3104                 return retcode;
3105         if (retcode != NO_ERROR)
3106                 goto out;
3107
3108         set_res_opts_defaults(&res_opts);
3109         err = res_opts_from_attrs(&res_opts, info);
3110         if (err && err != -ENOMSG) {
3111                 retcode = ERR_MANDATORY_TAG;
3112                 drbd_msg_put_info(from_attrs_err_to_txt(err));
3113                 goto out;
3114         }
3115
3116         retcode = drbd_check_resource_name(adm_ctx.resource_name);
3117         if (retcode != NO_ERROR)
3118                 goto out;
3119
3120         if (adm_ctx.tconn) {
3121                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
3122                         retcode = ERR_INVALID_REQUEST;
3123                         drbd_msg_put_info("resource exists");
3124                 }
3125                 /* else: still NO_ERROR */
3126                 goto out;
3127         }
3128
3129         if (!conn_create(adm_ctx.resource_name, &res_opts))
3130                 retcode = ERR_NOMEM;
3131 out:
3132         drbd_adm_finish(info, retcode);
3133         return 0;
3134 }
3135
3136 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
3137 {
3138         struct drbd_genlmsghdr *dh = info->userhdr;
3139         enum drbd_ret_code retcode;
3140
3141         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3142         if (!adm_ctx.reply_skb)
3143                 return retcode;
3144         if (retcode != NO_ERROR)
3145                 goto out;
3146
3147         if (dh->minor > MINORMASK) {
3148                 drbd_msg_put_info("requested minor out of range");
3149                 retcode = ERR_INVALID_REQUEST;
3150                 goto out;
3151         }
3152         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
3153                 drbd_msg_put_info("requested volume id out of range");
3154                 retcode = ERR_INVALID_REQUEST;
3155                 goto out;
3156         }
3157
3158         /* drbd_adm_prepare made sure already
3159          * that mdev->tconn and mdev->vnr match the request. */
3160         if (adm_ctx.mdev) {
3161                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3162                         retcode = ERR_MINOR_EXISTS;
3163                 /* else: still NO_ERROR */
3164                 goto out;
3165         }
3166
3167         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3168 out:
3169         drbd_adm_finish(info, retcode);
3170         return 0;
3171 }
3172
3173 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3174 {
3175         if (mdev->state.disk == D_DISKLESS &&
3176             /* no need to be mdev->state.conn == C_STANDALONE &&
3177              * we may want to delete a minor from a live replication group.
3178              */
3179             mdev->state.role == R_SECONDARY) {
3180                 _drbd_request_state(mdev, NS(conn, C_WF_REPORT_PARAMS),
3181                                     CS_VERBOSE + CS_WAIT_COMPLETE);
3182                 idr_remove(&mdev->tconn->volumes, mdev->vnr);
3183                 idr_remove(&minors, mdev_to_minor(mdev));
3184                 del_gendisk(mdev->vdisk);
3185                 synchronize_rcu();
3186                 kref_put(&mdev->kref, &drbd_minor_destroy);
3187                 return NO_ERROR;
3188         } else
3189                 return ERR_MINOR_CONFIGURED;
3190 }
3191
3192 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3193 {
3194         enum drbd_ret_code retcode;
3195
3196         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3197         if (!adm_ctx.reply_skb)
3198                 return retcode;
3199         if (retcode != NO_ERROR)
3200                 goto out;
3201
3202         retcode = adm_delete_minor(adm_ctx.mdev);
3203 out:
3204         drbd_adm_finish(info, retcode);
3205         return 0;
3206 }
3207
3208 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3209 {
3210         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3211         struct drbd_conf *mdev;
3212         unsigned i;
3213
3214         retcode = drbd_adm_prepare(skb, info, 0);
3215         if (!adm_ctx.reply_skb)
3216                 return retcode;
3217         if (retcode != NO_ERROR)
3218                 goto out;
3219
3220         if (!adm_ctx.tconn) {
3221                 retcode = ERR_RES_NOT_KNOWN;
3222                 goto out;
3223         }
3224
3225         /* demote */
3226         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3227                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3228                 if (retcode < SS_SUCCESS) {
3229                         drbd_msg_put_info("failed to demote");
3230                         goto out;
3231                 }
3232         }
3233
3234         retcode = conn_try_disconnect(adm_ctx.tconn, 0);
3235         if (retcode < SS_SUCCESS) {
3236                 drbd_msg_put_info("failed to disconnect");
3237                 goto out;
3238         }
3239
3240         /* detach */
3241         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3242                 retcode = adm_detach(mdev, 0);
3243                 if (retcode < SS_SUCCESS || retcode > NO_ERROR) {
3244                         drbd_msg_put_info("failed to detach");
3245                         goto out;
3246                 }
3247         }
3248
3249         /* If we reach this, all volumes (of this tconn) are Secondary,
3250          * Disconnected, Diskless, aka Unconfigured. Make sure all threads have
3251          * actually stopped, state handling only does drbd_thread_stop_nowait(). */
3252         drbd_thread_stop(&adm_ctx.tconn->worker);
3253
3254         /* Now, nothing can fail anymore */
3255
3256         /* delete volumes */
3257         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3258                 retcode = adm_delete_minor(mdev);
3259                 if (retcode != NO_ERROR) {
3260                         /* "can not happen" */
3261                         drbd_msg_put_info("failed to delete volume");
3262                         goto out;
3263                 }
3264         }
3265
3266         /* delete connection */
3267         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3268                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3269                 synchronize_rcu();
3270                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3271
3272                 retcode = NO_ERROR;
3273         } else {
3274                 /* "can not happen" */
3275                 retcode = ERR_RES_IN_USE;
3276                 drbd_msg_put_info("failed to delete connection");
3277         }
3278         goto out;
3279 out:
3280         drbd_adm_finish(info, retcode);
3281         return 0;
3282 }
3283
3284 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info)
3285 {
3286         enum drbd_ret_code retcode;
3287
3288         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3289         if (!adm_ctx.reply_skb)
3290                 return retcode;
3291         if (retcode != NO_ERROR)
3292                 goto out;
3293
3294         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3295                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3296                 synchronize_rcu();
3297                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3298
3299                 retcode = NO_ERROR;
3300         } else {
3301                 retcode = ERR_RES_IN_USE;
3302         }
3303
3304         if (retcode == NO_ERROR)
3305                 drbd_thread_stop(&adm_ctx.tconn->worker);
3306 out:
3307         drbd_adm_finish(info, retcode);
3308         return 0;
3309 }
3310
3311 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3312 {
3313         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3314         struct sk_buff *msg;
3315         struct drbd_genlmsghdr *d_out;
3316         unsigned seq;
3317         int err = -ENOMEM;
3318
3319         if (sib->sib_reason == SIB_SYNC_PROGRESS) {
3320                 if (time_after(jiffies, mdev->rs_last_bcast + HZ))
3321                         mdev->rs_last_bcast = jiffies;
3322                 else
3323                         return;
3324         }
3325
3326         seq = atomic_inc_return(&drbd_genl_seq);
3327         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3328         if (!msg)
3329                 goto failed;
3330
3331         err = -EMSGSIZE;
3332         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3333         if (!d_out) /* cannot happen, but anyways. */
3334                 goto nla_put_failure;
3335         d_out->minor = mdev_to_minor(mdev);
3336         d_out->ret_code = NO_ERROR;
3337
3338         if (nla_put_status_info(msg, mdev, sib))
3339                 goto nla_put_failure;
3340         genlmsg_end(msg, d_out);
3341         err = drbd_genl_multicast_events(msg, 0);
3342         /* msg has been consumed or freed in netlink_broadcast() */
3343         if (err && err != -ESRCH)
3344                 goto failed;
3345
3346         return;
3347
3348 nla_put_failure:
3349         nlmsg_free(msg);
3350 failed:
3351         dev_err(DEV, "Error %d while broadcasting event. "
3352                         "Event seq:%u sib_reason:%u\n",
3353                         err, seq, sib->sib_reason);
3354 }